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.rb
initializer file with these contents:
COLORS = YAML.load_file("#{Rails.root}/config/colors.yml")
This will load the contents of the configuration file into the COLORS
variable when the Rails application starts. Then you can access the colours from anywhere within the application using COLORS['section_name']['white']
etc. For example, you could do:
<h1 style="color: <%= COLORS['h1']['blue'] %>;">Main Heading</h1>
—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.
If the colors never change, it's okay to cache them. Follow this DZone tutorial.
3rd result for Google: ruby yaml tutorial
.
精彩评论