LoginSignup
0
0

More than 3 years have passed since last update.

ERB クラスを使って変数を展開した静的ファイルを作る

Last updated at Posted at 2020-08-08

ERBクラスを使って、Railsの html.erb ファイルみたいに変数展開したものを、静的ファイルとして保存したいと思います。

状況としては、例えば、ユーザーごとにプレファレンス設定で、好みのスタイルシートの設定を持っているんですが、一旦設定されれば、変更があるまではスタイルシート自体はそのユーザー専用の静的ファイルにして読み込んだ方が効率的であるということで。

例えば、こんな変数を含んだスタイルシートを書きます。

_style.css.erb
body {
  background-color: <%= bg_color %>;
}
.header {
  color: <%= title_color %>;
}
.text {
  color: <%= text_color %>
}

ActiveRecordで読み込んだプレファレンス設定が、
@preference というオブジェクト変数で、@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)

のようにして変数を展開した静的ファイルを得ることができます。

最初、単純にインスタンス変数 @preference を展開してくれるかなと思ったのですが、ファイルからテンプレートを読んでいるせいか、それはできず、hashとして渡すメソッドを使いました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0