在Ruby on Rails中为属性定义ghost方法

时间:2013-12-10 06:39:32

标签: ruby-on-rails ruby attr-accessor

我希望能够在数据库中没有相应的属性时动态添加

attr_accessor

这覆盖了我目前拥有的属性:

def method_missing(method, arg)
  self.class.attr_accessor.send(method) || super
end

我也尝试将变量加载到单例类中,但这给了我一个0的1参数错误。

1 个答案:

答案 0 :(得分:1)

那是你想要的吗?

def method_missing(method, *args)
  if method.to_s['=']
    self.define_singleton_method(method) do |*args|
      self.instance_variable_set("@#{method[0..-2]}", args.first)
    end
  else
    self.define_singleton_method(method) do
      self.instance_variable_get("@#{method}")
    end
  end
  self.send(method, *args) rescue super
end