A Great Example of Vendor-Library Abstraction in ActiveSupport

June 18, 2012 Mark Rushakoff

Depending on what you’re working on, you may have been bitten at least once by a heavy dependency on a third-party library.
This happens when you become very dependent on the API of someone else’s library, and suddenly you can no longer use that library or its API.

When this is a possibility, the defensive approach to this problem is to write your own API to wrap that API, so that if you need to drop that vendor library, you only have to reimplement the way your wrapper works.

You might think that you only need to worry about this in large, complicated APIs, but it can be worthwhile to do even for a simple API.

ActiveSupport::JSON uses MultiJSON behind the scenes.
Even though ActiveSupport::JSON has really only two publicly available “normal-use” methods (encode and decode which transform Ruby hashes back and forth with JSON objects), the Rails developers were wise enough to even wrap the specific error class that MultiJSON raises, as ActiveSupport::JSON.parse_error.

# File activesupport/lib/active_support/json/decoding.rb, line 50
def parse_error
  MultiJson::DecodeError
end

This way, you can write something like

begin
  obj = ActiveSupport::JSON.decode(some_string)
rescue ActiveSupport::JSON.parse_error
  Rails.logger.warn("Attempted to decode invalid JSON: #{some_string}")
end

And then if/when Rails switches from MultiJSON, you won’t have to change anything in your code to deal with exception handling around JSON.

(PS.
I wrote the documentation for that method recently, so that’s why I had to link to the Edge Guides.
If you haven’t seen it, check out my article on how easy it is to contribute to the Rails documentation.)

About the Author

Biography

Previous
git rebase –onto
git rebase –onto

"Hold on to your butts.." --Samuel L. Jackson as Ray Arnold in 'Jurassic Park' Part One: The tw...

Next
Tuesday Brown Bag: @ykatz
Tuesday Brown Bag: @ykatz

Events Tuesday Brown Bag: Yehuda Yehuda Katz will be giving a brown bag on Tuesday at 12:30.