Adam
Adam

Reputation: 101

Define class methods inside Active Record class

Settings table from schema:

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

Settings table has these records:

{name: "notification_email", value: "[email protected]"}
{name: "support_phone", value: "1234567"}

I want the Setting.notification_email function to return "[email protected]" and respectively the Setting.support_phone function to return "1234566".

Here is what I have in my 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

But then when I enter Setting.notification_email in console, it gives me an error:

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)>'
    ...

Upvotes: 3

Views: 738

Answers (1)

dlangevin
dlangevin

Reputation: 374

Use define_singleton_method - i.e.

class Setting < ActiveRecord::Base

  self.all.each do |instance|
    define_singleton_method(instance.name) do
      instance.value.to_s
    end
  end
end

Upvotes: 3

Related Questions