Bryan Lee

HTTParty and Rails Caching Gotcha

· Web Dev

If you try to cache a HTTParty response directly, you find that you run into some strange error quickly.

This works fine and returns a normal HTTParty object response:

HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow')

But try this now and your world crumbles apart:

Rails.cache.fetch("stackoverflow/questions", expires_in: 1.hour) do
HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow')
end

# Error response
TypeError: no _dump_data is defined for class Proc

More info can be found in @tvon's explanation in this Github issue and this StackOverflow, but generally, what happened is that the response by HTTParty cannot be serialized by Rails cache.

To resolve this, we just need to convert the response into something Rails can serialize:

Rails.cache.fetch("stackoverflow/questions/#{Time.zone.now}", expires_in: 1.second) do
HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow').to_h
HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow').to_a
HTTParty.get('http://api.stackexchange.com/2.2/questions?site=stackoverflow').to_json
end

Converting to a hash, array or JSON string all works fine, depending on whichever is more suitable for your needs. I took the chance to use an OpenStruct instead to make things even more convenient though!