简体   繁体   中英

What's the best way to map internal rails models to an external API?

Whats the best way, to map your internal Rails models to external APIs?

Example

For eg if I have a model called Car with an attribute called color which in my case holds a bunch of different possible values like

- "red"
- "blue"
- "black"
- "green"
- ...

And now I might have to send an object of my class to another applications API which also knowns about cars but their colors are encoded in numbers or different codes like so:

- 0 == "black"       or       "Black paint" == "black"
- 1 == "white"       or       "White paint" == "white"
- 2 == "red"         or         "Red paint" == "red"
- ...

Is there some nifty way to map those values within Rails except with huge switch: ... case: ... assignments?

You can make a hash... I'd be likely to put it in the Car model

API_COLORS = {'black' => 'inky', 'white' => 'snow'}

And you mioght want to use the hash only for colors encoded in the hash, in which cas you can then have an instance method in the Car moddel that returns the API_COLORS value if it exists, otherwise returns the normal color value.

def api_color
  API_COLORS[color] || color
end

And in your API you would send my_car.api_color

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM