0

I'd like to create a Settings model centered around a "settings" database table in my Ruby app. The table looks like this:

==========================
id  | key          | value
==========================
1   | site_version | 1.0.5
2   | something    | value

I'd like to be able to access each row in this table via this Settings model just like I would a normal Ruby hash. So I could use Settings.site_version or Settings['site_version'] to access the "site_version" value.

I know I've seen something like this before, but I'm not seeing anything out there. How would I achieve this? A link to a blog article would also suffice.

Chad Johnson
  • 21,215
  • 34
  • 109
  • 207

1 Answers1

1

You can define a class method in Setting model,

def self.my_method(key)
  where(key: key).first.try(:value)
end

and you can access values like my_method('site_version')

If you really want a Hash:

Assuming you dont have a lot of records and all the keys are unique, you can do

settings = Hash[ Setting.all.map {|s| [s.key, s.value]} ]

settings is a Hash, and you can access the values like settings['site_version']

Note: If you have other attributes in settings table, dont forget to use select on the query.

Santhosh
  • 28,097
  • 9
  • 82
  • 87