【问题标题】:Define class methods inside Active Record class在 Active Record 类中定义类方法
【发布时间】:2012-04-10 02:07:12
【问题描述】:

来自架构的设置表:

create_table "settings", :force => true do |t|
  t.string   "name"
  t.string   "value"
  t.datetime "created_at"
  t.datetime "updated_at"
end

设置表有这些记录:

{name: "notification_email", value: "hello@monkey.com"}
{name: "support_phone", value: "1234567"}

我希望 Setting.notification_email 函数返回“hello@monkey.com”,并分别让 Setting.support_phone 函数返回“ 1234566”。

这是我的 setting.rb 中的内容:

class Setting < ActiveRecord::Base
  class << self
    all.each do |setting|
      define_method "#{setting.name}".to_sym do
        setting.value.to_s
      end 
    end 
  end 
end

但是当我在控制台中输入 Setting.notification_email 时,它给了我一个错误:

NameError: undefined local variable or method `all' for #<Class:0x000000053b3df0>
    from /home/adam/Volumes/derby/app/models/setting.rb:7:in `singletonclass'
    from /home/adam/Volumes/derby/app/models/setting.rb:2:in `<class:Setting>'
    from /home/adam/Volumes/derby/app/models/setting.rb:1:in `<top (required)>'
    ...

【问题讨论】:

    标签: ruby-on-rails ruby metaprogramming


    【解决方案1】:

    使用define_singleton_method - 即

    class Setting < ActiveRecord::Base
    
      self.all.each do |instance|
        define_singleton_method(instance.name) do
          instance.value.to_s
        end
      end
    end
    

    【讨论】:

    • define_singleton_method 适用于 1.9。 1.8 中的等价物是 self.class.instance_eval 与之前的 define_method 组合。很高兴这已经被清理了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2014-01-26
    • 2013-02-18
    • 1970-01-01
    • 2014-02-16
    相关资源
    最近更新 更多