ruby-on-rails – 如何在rails中缓存计算列?

我有一棵活动记录对象的树,像:
class Part < ActiveRecord::Base
  has_many :sub_parts,:class_name => "Part"

  def complicated_calculation
    if sub_parts.size > 0
      return self.sub_parts.inject(0){ |sum,current| sum + current.complicated_calculation }
    else
      sleep(1)
      return rand(10000)
    end
  end

end

每次重新计算complex_calculation成本太高.所以,我需要一种缓存值的方法.然而,如果任何部分被更改,它需要使其缓存和其父代和祖父母等的缓存无效.

作为一个粗略的草稿,我创建了一个列,以将缓存的计算保存在“parts”表中,但是这味道有点烂.似乎应该有一个更清洁的方法来缓存计算值,而不是将它们填充在“真实”列的旁边.

解决方法

>您可以在Rails缓存中填充实际缓存的值(如果需要分发,请使用memcached).
>难点是缓存到期,但缓存到期不常见,对吧?在这种情况下,我们可以依次循环遍历每个父对象,并对其缓存进行zap.我添加了一些ActiveRecord魔法到你的类,使得父对象的简单性本身 – 而你甚至不需要触摸你的数据库.记得在您的代码中适当调用Part.sweep_complicated_cache(some_part) – 您可以将其放在回调等中,但是我无法为您添加它,因为当complex_calculation发生变化时,我不明白.
class Part < ActiveRecord::Base
  has_many :sub_parts,:class_name => "Part"
  belongs_to :parent_part,:class_name => "Part",:foreign_key => :part_id

  @@MAX_PART_nesTING = 25 #pick any sanity-saving value

  def complicated_calculation (...)
    if cache.contains? [id,:complicated_calculation]
      cache[ [id,:complicated_calculation] ]
    else
      cache[ [id,:complicated_calculation] ] = complicated_calculation_helper (...)
    end
  end

  def complicated_calculation_helper
    #your implementation goes here
  end

  def Part.sweep_complicated_cache(start_part)
    level = 1  # keep track to prevent infinite loop in event there is a cycle in parts
    current_part = self

    cache[ [current_part.id,:complicated_calculation] ].delete
    while ( (level <= 1 < @@MAX_PART_nesTING) && (current_part.parent_part)) {
     current_part = current_part.parent_part)
     cache[ [current_part.id,:complicated_calculation] ].delete
    end
  end
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...