Implementing dynamic methods in rails for key/value pair

225 Views Asked by At

Let's say I have a database table called 'options' with corresponding model called Option. Structure of this table is simple and as follows ...

id    -> primary key, auto increment
name  -> key
value -> value for the key

Sample data rows could be as follows ...

id   name                         value     
---- ---------------------------- -----------
1    default_view                 DAILY     
2    show_registration_number     0         
3    notification_method          IMMEDIATE     

What I want is that all the options (keys) should be accessible to me as the method names.

For example if do as following ...

@options = Options.find(:all)

is it possible to access the data like @options.default_view which should return me the value as 'DAILY' and similarly @options.show_registration_number which should return the value as 0.

Also if that is possible, whether modification would be permissible like if @options.default_view = 'MONTHLY' and should update the corresponding record in the database.

1

There are 1 best solutions below

0
On

This will get you almost the answer you were looking for: http://code.dblock.org/how-to-define-enums-in-ruby

It relies on const_missing and assumes that elements of your "enum" are defined as constants, in your case Option::default_view

However, it is easy to see how to adapt this code to use method_missing so that you can do Option.default_view

Another example of this same approach is contained in rails-settings gem, so you can browse this code for the answer you are looking for