LoginSignup
60
58

More than 5 years have passed since last update.

[Rails 4.x] Viewでアクションごとの条件分岐を綺麗に書く小技

Posted at

完全に小ネタの投稿ですが、Ruby on Railsのviews/layout/application.html.erbなどで、
特定のコントローラ/アクションでは表示したいけど、他ではいらないみたいな要素があるとき、
素直に実装するなら、

<% if controller.controller_name == 'pages' && controller.action_name == 'index' %>
    <a href="#">メニュー</a>
<% end %>

みたいな書き方になって、かなり面倒くさくなるので、あらかじめ、

# controllers/application.rb
before_action :request_path
def request_path
    @path = controller_path + '#' + action_name
    def @path.is(*str)
        str.map{|s| self.include?(s)}.include?(true)
    end
end

という風に書いておけば、Viewから参照するときに、

<% if @path.is('pages#index') %>
    <a href="#">コントローラがpagesで、アクションがindexの時</a>
<% end %>

と書けるし、以下みたいに色々応用が利く。

<% if @path.is('admin/users#add') %>
    <a href="#">名前空間がadminで、コントローラがusersで、アクションがadd</a>
<% end %>
<% if @path.is('pages#index', 'pages#add') %>
    <a href="#">コントローラがpagesで、アクションがindexまたはadd</a>
<% end %>
<% if @path.is('pages#') %>
    <a href="#">コントローラがpages</a>
<% end %>
<% if @path.is('#index') %>
    <a href="#">アクションがindex</a>
<% end %>

ちょっとした小技だけど、コーディングのストレスが減るのでおすすめです。

60
58
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
60
58