[Ruby] Create a static file that expands variables using ERB class

less than 1 minute read

I’d like to save the variable expanded like a Rails html.erb file as a static file using the ERB class.

As a situation, for example, each user has their own preference sheet settings in preference settings, but once set, the style sheet itself is a static file dedicated to that user until changed. It is more efficient to read in.

For example, write a stylesheet that includes 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 @preference.bg_color, @preference.title_color, @preference.text_color in an object variable called @preference

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 the static file which expanded the variable as follows.

At first, I was wondering if it would simply expand the instance variable @preference, but I couldn’t because I was reading the template from a file, so I used the method passed as hash.

Tags:

Updated: