How can I put (parts of) a large object graph in Rails.cache?

I have a class in which looking up an instance is expensive, so instances are cached:

class Foo
  def self.find(id)
    Rails.cache.fetch("Foo.#{id}") do
      // some expensive lookup, like an HTTParty request, or a long SQL query
      ...
    end
  end
end

That works fine until Foos have related Foos:

class Foo
  def children
    @child_foo_ids.map { |id| Foo.find(id) }
  end
end

I'd like to use ||= caching to save repeated trips:

class Foo
  def children
    @children ||= @child_foo_ids.map { |id| Foo.find(id) }
  end
end

But Rails.cache freezes the found Foos, so I can't set the instance variable after I create and cache the object. (i.e. this method raises a TypeError.)

One solution would be to pre-fetch the parent when I first do the expensive find, but that could end up loading a gigantic object graph when I only want one or two instances.

Answers


You can use ||= caching; you just have to use a little indirection:

class Foo
  def initialize
    @related_objects = {}
  end
  def children
    @related_objects[:children] ||= @child_foo_ids.map { |id| Foo.find(id) }
  end
end

Rails.cache won't freeze the instance variables of each Foo, so that Hash can be modified!

PS: yes, I did just post this question and the answer at essentially the same time. I figured the community could benefit from my struggle.


Need Your Help

White flash when multiple css background-images are changed through jQuery

javascript jquery html css image

I`ve got a page with multiple css background-images. Every time you click a dot (the first three dots are working on the bottom) a new image comes in via jQuery.

Multiple instances of a singleton class... very strange behavior

java android singleton

I have a class which implements the Singleton pattern. I need an instance of this class in an Activity and in a fragment (hosted by the activity).