Rails:为缓存检索模型添加额外的方法



在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引入缓存,我发现自己在模型中添加方法,这是超级重复的:

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在这一点上实际上是多余的。如何才能将其清理干净?

创建一个mixin,只提供围绕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)那样做,那么你的问题突然变得不那么重复了

最新更新