true do |t| t.string "na...">

Defining Class Methods in an Active Record Class

Settings table from the diagram:

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

      

The settings table contains the following entries:

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

      

I want the Setting.notification_email function to return " hello@monkey.com " and the Setting.support_phone function to return " 1234566 " accordingly .

Here's what I have in my .rb setup :

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 Set.notification_email in the 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)>'
    ...

      

+3


source to share


1 answer


Use define_singleton_method - ie



class Setting < ActiveRecord::Base

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

      

+3


source







All Articles