I'm not sure if this can even be achieved, but here goes... :)
Lets assume two models, a Page
model and a Field
model. A Page has_many :fields
and the Field
model has two attributes: :name, :value
What I want to achieve is in the Page
model to dynamically define instance methods for each Field#name
returning the Field#value
.
So if my page had a field with a name of "foobar", I would dynamically create a method like so:
def foobar
fields.find_by_name("foobar").value
end
Can this be achieved? If so, please help?
Over to the rubyists...
You can override method_missing to achieve your goal:
def method_missing(method, *args, &block)
super
rescue NoMethodError => e
field = fields.find_by_name(method)
raise e unless field
field.value
end
Probably it's better to add prefix or suffix to your dynamic methods, eg:
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
And call it like:
page.value_of_foobar
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.