Tom Hammond
Tom Hammond

Reputation: 6090

Rails mapping attributes to outside source values in most efficient manner

I'm trying to figure out the best way to map model attributes to a set of values in an outside service as part of an integration we're doing with them.

For example, let's say our User model has an education_level attribute with values in our system that we store as 0, 1, 2, 3, 4, 5 and they equate to:

0  8th grade education
1  high school education
2  associate's degree
3  some college
4  bachelor's degree
5  masters or phd degree

in their system, they are say 343, 344, 355, 356, 363 and 373. So I want some sort of mapping table like:

0  343
1  344
2  355
3  356
4  363
5  373

And when I do a POST to the external system, we send 344 if the user has 1 stored for high school education.

I know I could store this in just a txt or csv file and do a File.open and loop through every line and check to see if the values match. But that doesn't really seem very efficient, especially if there are a lot of values that are possible.

Thoughts on how to accomplish this sort of mapping in the most efficient way?

Upvotes: 0

Views: 52

Answers (1)

mpospelov
mpospelov

Reputation: 1549

You should use a Hash in this case:

class User
  SERVICE_EDUCATION_LEVELS_MAP = {
    0 => 343,
    1 => 344,
    2 => 355,
    3 => 356,
    4 => 363,
    5 => 373
  }.freeze

  def service_education_level
    SERVICE_EDUCATION_LEVELS_MAP[education_level]
  end
...
end

Now you can access this mapping by calling #service_education_level on User instance.

Upvotes: 1

Related Questions