Rails - dynamically defining instance methods in a model

I'm not sure that this can be achieved, but here it goes ... :)

Suppose two models, model Pageand model Field. A Page has_many :fieldsand model Fieldhave two attributes::name, :value

What I want to achieve is in the model Pagefor dynamically defining instance methods for each Field#namereturning one Field#value.

So, if there was a field named "foobar" on my page, I would dynamically create a method like this:

def foobar
  fields.find_by_name("foobar").value
end

Can this be achieved? If yes, please help?

To rubists ...

+3
source share
1 answer

method_missing :

def method_missing(method, *args, &block)
  super
rescue NoMethodError => e
  field = fields.find_by_name(method)
  raise e unless field
  field.value
end

, , :

def method_missing(method, *args, &block)
  if method.starts_with?('value_of_')
    name = method.sub('value_of_', '')
    field = fields.find_by_name(method)
    field && field.value
  else
    super
  end
end

:

page.value_of_foobar
+1

Source: https://habr.com/ru/post/1761600/


All Articles