I would like to use the ERB class to expand variables like the Rails html.erb file and save it as a static file.
The situation is, for example, each user has his or her favorite stylesheet settings in the preferences settings, but once set, the stylesheet itself is a static file dedicated to that user until there is a change. It is more efficient to read it as.
For example, write a stylesheet that contains these variables.
css:_style.css.erb
body {
background-color: <%= bg_color %>;
}
.header {
color: <%= title_color %>;
}
.text {
color: <%= text_color %>
}
The preference settings read by ActiveRecord are If you have an object variable called @preference with @ preference.bg_color, @ preference.title_color, @ preference.text_color
style_erb = ERB.new(File.read("_style.css.erb"))
style_res = style_erb.result_with_hash(@preference.attributes)
File.write("style_#{@preference.user_id}.css", style_res)
You can get a static file with the variables expanded as follows.
At first, I thought it would simply expand the instance variable @preference, but I couldn't do that, probably because I was reading the template from a file, so I used the method I passed as hash.
Recommended Posts