【发布时间】:2012-08-18 12:46:41
【问题描述】:
我编写了一个简单的 Cacheable 模块,它使得在父模型中缓存聚合字段变得简单。该模块要求父对象实现cacheable方法,并为每个需要在父级别缓存的字段实现calc_方法。
module Cacheable
def cache!(fields, *objects)
objects.each do |object|
if object.cacheable?
calc(fields, objects)
save!(objects)
end
end
end
def calc(fields, objects)
fields.each { |field| objects.each(&:"calc_#{field}") }
end
def save!(objects)
objects.each(&:save!)
end
end
我想向包含此模块的 ActiveRecord 模型添加回调。此方法需要模型实现需要缓存的父模型和字段名称的哈希。
def cachebacks(klass, parents)
[:after_save, :after_destroy].each do |callback|
self.send(callback, proc { cache!(CACHEABLE[klass], self.send(parents)) })
end
end
如果我使用以下方法手动添加两个回调,这种方法效果很好:
after_save proc { cache!(CACHEABLE[Quote], *quotes.all) }
after_destroy proc { cache!(CACHEABLE[Quote], *quotes.all) }
但是,当我尝试使用 cachebacks 方法将这些添加到回调时,我收到以下错误。
cachebacks(Quote, "*quotes.all")
NoMethodError: undefined method `cachebacks' for #<Class:0x007fe7be3f2ae8>
如何将这些回调动态添加到类中?
【问题讨论】:
-
抱歉,我无法理解最后一部分。
Quote是相关型号吗?您能否发布一下您的班级现在的情况? -
我根据您的提示得出的答案应该可以解释问题。我也对 ActiveSupport::Concern 方法感兴趣。
标签: ruby-on-rails ruby metaprogramming