Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

A Great Example of Vendor-Library Abstraction in ActiveSupport

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

This way, you can write something like

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

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.

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.)

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *