1
0

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 5 years have passed since last update.

ERBで'<%='の前にある空白文字を取り除くシンプルな方法は用意されていない...のか?

Posted at

リファレンス

基本形
> ERB.new("<%= :hoge %>").result  # => "hoge"
> ERB.new("    <%= :hoge %>    \n").result  # => "    hoge    \n"
後ろを消したい

リファレンスによれば、trim_modeを"-"にした場合、「行末が-%>のとき改行を出力しない」。

> ERB.new("<%= :hoge %>\n", trim_mode: '-').result  # => "hoge\n"
> ERB.new("<%= :hoge -%>\n", trim_mode: '-').result  # => "hoge"

しかし、-%>が行末にない場合は後続のスペースも改行も消されない。

> ERB.new("<%= :hoge -%>    \n", trim_mode: '-').result  # => "hoge    \n"
前を消したい

リファレンスによると「行頭が<%-のとき行頭の空白文字を削除する」

> ERB.new("    <%- nil %>hoge", trim_mode:  '-').result  # => "hoge"

<%=の前にある空白文字って消せないのかな?

<%=-, <%-=のように組み合わせてもダメ。

> ERB.new("    <%=- :hoge %>", trim_mode:  '-').result
# => NoMethodError (undefined method `-@' for :hoge:Symbol)
> ERB.new("    <%-= :hoge %>", trim_mode:  '-').result
# => SyntaxError ((erb):1: syntax error, unexpected '=', expecting end-of-input)

どうやら<%=の前にある空白文字を取り除くシンプルな方法は用意されていないらしい。

同じ疑問をもっている方がいた。

ここで提示された解決策は以下。

> ERB.new("    <%- %><%= :hoge %>", trim_mode:  '-').result  # => "hoge"

強引さが否めない...。

ちなみに

Railsでメールのテンプレートを"xx.text.erb"でつくっていて、

<% @users.each do |user| %>
  <%= user.name %>
  <%= user.age %>
<% end %>

みたいな場合にブロック内の行頭の空白文字を消したくて方法を探してたのだけど、これってわりと一般的なニーズなのでは?

(メソッド化するとか、<%をインデントしないとか、やりようはいくらでもあるとおもうけど。)

githubのruby/rubyでissueを検索したけどなさそう。

issueを立てるに値する話だったらとっくに誰かがやってる気がするので、

  • 実はこの問題は解決できる
  • そもそもこの問題が生じるのがおかしい(やりたいことの設定がおかしい)

のどちらかな気がするけどどうなんでしょうか。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?