Jam*_*sen 0 ruby caching ruby-on-rails
我有一个类,其中查找实例很昂贵,因此实例被缓存:
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
Run Code Online (Sandbox Code Playgroud)
这有效,直到Foos有相关的Foos:
class Foo
def children
@child_foo_ids.map { |id| Foo.find(id) }
end
end
Run Code Online (Sandbox Code Playgroud)
我想使用||=缓存来节省重复的旅行:
class Foo
def children
@children ||= @child_foo_ids.map { |id| Foo.find(id) }
end
end
Run Code Online (Sandbox Code Playgroud)
但Rails.cache冻结了找到的Foos,所以在创建和缓存对象后我无法设置实例变量.(即这种方法提出了一个TypeError.)
一种解决方案是parent在我第一次执行昂贵的查找时预先获取,但是当我只需要一个或两个实例时,最终可能会加载一个巨大的对象图.
你可以使用||=缓存; 你只需要使用一点间接:
class Foo
def initialize
@related_objects = {}
end
def children
@related_objects[:children] ||= @child_foo_ids.map { |id| Foo.find(id) }
end
end
Run Code Online (Sandbox Code Playgroud)
Rails.cache不会冻结每个的实例变量Foo,所以Hash可以修改!
PS:是的,我刚刚在同一时间发布了这个问题和答案.我认为社区可以从我的斗争中受益.
| 归档时间: |
|
| 查看次数: |
371 次 |
| 最近记录: |