I’m using rails to build a website.
I have a yaml file contails some colors, which is config/colors.yml
---
- white
- red
- blue
- yellow
- ...
And, there is an erb file app/views/users/setting.html.erb, which will need the data in config/colors.yml, and put them in a tag.
I don’t know what’s the correct way to read the yaml file. Can I read once and store them in memory, or I should read it each time the page is requested?
Create a
config/initializers/load_colors.rbinitializer file with these contents:This will load the contents of the configuration file into the
COLORSvariable when the Rails application starts. Then you can access the colours from anywhere within the application usingCOLORS['section_name']['white']etc. For example, you could do:—Although using an inline style like this within a view template isn’t really good practice, but it gives you an idea of the usage.