开发者

What's the correct way to read some data from a yaml file and use it in an erb page?

开发者 https://www.devze.com 2023-01-05 23:34 出处:网络
I\'m using rails to build a website. I have a yaml file contails some colors, which is config/colors.yml

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.

开发者_如何学JAVA

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号