6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Tips]ERBで自由にファイルを作ってみる

Posted at

erb、と聞くとrailsのフロントエンドで使われている印象ですが、実はそれ以外にも応用が効く優れものです。
この記事ははerbテンプレートに変数を入力することでファイルを作成してみます。

まずerbをインストールする

gem installbundle installでerbをインストールします。

ここはお好みで。

テンプレートファイルを作成する

erbテンプレートを作成します。今回は説明を簡単にするために、簡単なerbファイルを作成します。

sample.rb
<%= @number %>

erbテンプレートからファイルを作成してみる

先ほど作成したerbテンプレートから実際にrubyコードを書いてファイルを出力してみます。
今回はRake taskとして作成してみます。

Rakefile
# frozen_string_literal: true

require 'erb'

task :sample do
  erb = ERB.new(
    File.read('sample.erb')
  )
  @number = 1
  filename = "#{number}.txt"
  File.write(filename, erb.result)
end

行っている処理としては、ERB.new()でerbファイルの中身を文字列として読み込み、erb.resultが実行されるときに、変数などを代入した結果の文字列をファイルに出力しています。

bundle exec rake sampleを実行することで今回は@numberに1を代入しているので、1という文字列が出力された1.txtが作成されます。

まとめ

今回は簡単なサンプルを用いてerbから簡単なファイル生成を行ってみました。
冒頭にも書いた通りerbはフロントエンドで利用されている印象が強いですが、テンプレートエンジンとしてこのような用途もあるので、何かテンプレートを作成するときに利用してみるのはいかがでしょうか?

6
1
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
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?