2012-04-10 54 views
3

設置表:定義的Active Record類的內部類中的方法從架構

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: "[email protected]"} 
{name: "support_phone", value: "1234567"} 

我想Setting.notification_email函數返回「你好@ monkey.com「和Setting.support_phone函數返回」「。

以下是我在我的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)>' 
    ... 

回答

3

使用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 
+0

'define_singleton_method'爲1.9。與之前一樣,1.8中的等價物是'self.class.instance_eval'和'define_method'。很高興這已被清理。 – tadman 2012-04-10 02:14:23