Setting model 有 name 和 value 两个字段,用来存储站点的相关设置,比如
name | value |
---|---|
site_title | xxxx |
site_description | xxxxx |
site_url | xxxxx |
如果要获取某个设置项的值,需要这么写
Setting.find_by_name('site_title').value
我想直接用 Setting.site_title
来获取设置项,于是我重写了 method_missing
class Setting < ActiveRecord::Base
validates_presence_of :name, :value
validates_uniqueness_of :name
class << self
alias :old_method_missing :method_missing
def method_missing(method, *arg)
setting = find_by_name(method)
# 如果能找到,就返回 value
if setting.nil?
setting.value
else
# 否则调用原来的 method_missing
old_method_missing(method, *arg)
end
end
end
end
但是这样之后,就会显示 stack level too deep
pry(main)> Setting.site_title
SystemStackError: stack level too deep
from /usr/lib/ruby/gems/2.1.0/gems/pry-0.10.0/lib/pry/pry_instance.rb:353
请问这个是怎么回事?