ヘルパーで部分テンプレート(パーシャル)を返す方法
if文を使って条件ごとに異なるパーシャルを返したい場合があると思います。
しかし"html.erb"ファイルの中でif文を書くとどうしてもコードが長くなってしまいますよね。
例えばこんな風に、、、
sample.html.erb
<% if A == A %>
<%= render 'follow_button' %>
<% else %>
<%= render 'unfollow_button' %>
<% end %>
こんな時はヘルパーメソッドに処理をまとめるとスッキリします。⬇︎
users_helper.rb
module UsersHelper
def follow_unfollow_button(user)
if A == A
render 'follow_button'
else
render 'unfollow_button'
end
end
end
ビューでhelperメソッドを使うと、、
sample.html.erb
<%= follow_unfollow_button(@user) %>
1行でスッキリしました。
まとめ
slimやhamlを使用していればif文も多少は短くなるのですが、いずれにせよビューの中にロジックが書かれているとやはりコードの可読性が下がってしまいます。
できるだけif文などのロジックやhelperやdecoratorにまとめた方が良いと思いました。