Bryan Lee

HTTParty and Rails Caching Gotcha

· Ruby on Rails

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:


But try this now and your world crumbles apart:

Rails.cache.fetch("stackoverflow/questions", expires_in: 1.hour) do

# 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/#{}", expires_in: 1.second) do

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!