Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 737
Freewind Avatar asked Jul 08 '10 13:07

Freewind


1 Answers

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.

like image 61
John Topley Avatar answered Sep 18 '22 14:09

John Topley