2012-04-10 14 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は" "。

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をここで

は、私は私のsetting.rbに持っているものです - すなわち

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

関連する問題