在 Rails 中向模型添加缓存时,会出现如下所示的重复性:
class Team < ActiveRecord::Base
attr_accessible :name
end
Before caching, to retrieve a name, everything was trivial,
team = Team.new(:name => "The Awesome Team")
team.save
team.name # "The Awesome Team"
通过使用 memcached 或 redis 引入缓存,我发现自己向我的模型添加了方法,而且它是 super 重复的:
def get_name
if name_is_in_cache
return cached_name
else
name
end
end
def set_name(name)
# set name in cache
self.name = name
end
我是否缺少一些明显的方法来清理它?我以不同的方式缓存了很多字段,看起来 attr_accessible
在这一点上实际上是多余的。如何清理?
最佳答案
创建一个仅提供 instance_eval
包装器的混合宏。未经测试:
module AttributeCaching
def cache(name)
instance_eval(<<-RUBY)
def get_#{name}
if #{name}_is_in_cache
return cached_#{name}
else
#{name}
end
end
RUBY
instance_eval(<<-RUBY)
def set_#{name}(name)
self.#{name} = name
end
RUBY
end
end
然后在你的模型中:
class Team < ActiveRecord::Base
extend AttributeCaching
cache :name
cache :something_else
end
不过,如果不以不同方式命名每个缓存方法,您可能会让生活变得更轻松。你不能做像 get_cached(name)
和 set_cached(name, value)
这样的事情,然后你的问题突然变得不那么重复了。
关于ruby-on-rails - rails : adding additional methods to a model for cache retrieval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7576690/