8
6

More than 5 years have passed since last update.

RailsのHelperにブロックを渡す

Last updated at Posted at 2014-01-27

「特定の条件を満たした時に中身を表示、満たしていないときには何も出さない」という処理を、同じ条件で中身は違うというものをいろんなところに書きたかったのでHelperに実装してみました。

some_view.html.haml
= lock do
  条件を満たした!

erbなら以下のようになると思います。

some_view.html.erb
<%= lock do %>
  条件を満たした!
<% end %>

としておいて、helper側は以下のようにします。

application_helper.rb
def lock(&block)
  if some_condition?
    capture(&block)
  else
    '今は見れません!'
  end
end

capture(&block) がミソですね。

block_called_from_erb?はRails3からは天に召されているので注意。

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