Ruby 请教一下~关于 ruby-china 中 SiteConfig 的问题。

tassandar · 2012年02月16日 · 最后由 tassandar 回复于 2012年02月16日 · 3278 次阅读

新手,最近在看 ruby-china 的代码,看到了关于站点默认设置的 Siteconfig 类哪里有一点小问题,求教。 代码在这里

# coding: utf-8
# 在数据库中的配置信息
# 这里有存放首页,Wiki 等页面 HTML
# 使用方法
# SiteConfig.foo
# SiteConfig.foo = "asdkglaksdg"
class SiteConfig
  include Mongoid::Document

  field :key
  field :value

  index :key

  validates_presence_of :key
  validates_uniqueness_of :key

  def self.method_missing(method, *args)
    method_name = method.to_s
    super(method, *args)
  rescue NoMethodError
    if method_name =~ /=$/
      var_name = method_name.gsub('=', '')
      value = args.first.to_s
      # save
      if item = find_by_key(var_name)
        item.update_attribute(:value, value)
      else
        SiteConfig.create(:key => var_name, :value => value)
      end
    else
      Rails.cache.fetch("site_config:#{method}") do
        if item = where(:key => method).first
          item.value
        else
          nil
        end
      end
    end
  end

  after_save :expire_cache
  def expire_cache
    Rails.cache.write("site_config:#{self.key}", self.value)
  end

  def self.find_by_key(key)
    where(:key => key.to_s).first
  end

  def self.save_default(key, value)
    if not find_by_key(key)
      create(:key => key, :value => value.to_s)
    end
  end
end

1.这里的 self.method_missing 方法中的 的 super(method, *args) 是做什么用的呢,SiteConfig 的 supperclass 是什么? 2.

Rails.cache.fetch("site_config:#{method}") do
      if item = where(:key => method).first
        item.value
      else
        nil
      end
    end

这里为什么不直接返回 Rails.cache.fetch("site_config:#{method}") 呢,后面的 block 是做什么的呢? 3。

if item = where(:key => method).first

这句为什么使用 method 呢,我看保存的时候都是用 to_s 方法之后字符串,不应该用 method_name 或者 method.to_s 么?

  1. 这段代码有问题的,其实是多余的,之前是直接 Copy 一个设置组件的类似代码来实现 MongoDb 下面的配置信息功能。
  2. 这个地方就是这么写的啊
  3. method 这里就算不 .to_s 到了 Mongoid 那里也会 to_s 的,当然应该 to_s 一下才清楚。

@huacnlee 谢啦,转了一圈没找到 Rails.cache 的用法,能帮忙解释一下么? 后面那个 do ... end 中间的作用是什么呀。

试了一下,Rails.cache.fetch("site_config:#{method}") 好像就可以读出缓存的内容了,那后面那个 block 是不是如果没读出来就调用后面的 block?

#3 楼 @tassandar 里面也就是这样:

def fetch(key,&block)
  if not value = cache.get(key)
    value = yield
    cache.write(key,value)
  end
end

@huacnlee 恩恩。谢啦。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号