Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails static data set

What is the best way to handle a static data set (non-dynamic)?

For instance, let's say you have a model that has a set of 10 different instances, each of which is unique, but none of which will ever change throughout the lifetime of your application. It seems overkill to create an activerecord model and store this data in the database, but it seems ugly to create a generic class and store this data in the code.

What is accepted as a best practice?


Example:

You have a Rate and a User. A User can have a level from 1-10, when the level changes, the rate changes. The rate might have other information, so simply storing it as an attribute on the User might be more trouble than it's worth. Would it make sense to tie it to a Rate or to create it as a method on the User like this:

def rate
  case self.level
  when 1:
    { value: "foo", something: "bar", else: "baz" }
  when 2:
    # etc
  end
end

It seems that neither of the solutions are ideal, but I'm not sure if there is something else ideal that could happen.

like image 538
andrewpthorp Avatar asked Nov 14 '12 16:11

andrewpthorp


1 Answers

I would store this information in a YAML file. You could use the RailsConfig gem and create a YAML file like

level:
  1:
    some: value
    another: value
  2:
    some: second value
    another: second value

And then access it with

rate = 2
val = Settings.level[rate.to_s].some

(I'm not completely sure with numbers as keys in YAML, maybe you have to escape them)

like image 146
Sven Koschnicke Avatar answered Oct 15 '22 17:10

Sven Koschnicke