before action setter いる? / Good-bye "before action setter"
自分もbefore_action
でsetter
を定義する書き方は良くないと思っていて、自分の書き方を共有しておく。
class HogesController < ApplicationController
def show
end
def hoge
@hoge ||= Hoge.find_by!(id: params[:hoge_id])
end
end
private
修飾はせずにview
でもメソッドで呼び出し。
<%= controller.hoge %>
モデルの依存関係も同じように書ける。
class ApplicationController < ActionController::Base
def current_user
@current_user ||= User.set_current_user!
rescue
# 説明用として書くが、raiseは`set_current_user!`内に記述する。
raise Unauthorized, 'error message'
end
end
class BooksController < ApplicationController
def show
end
def book
@book ||= current_user.books.find_by!(id: params[:book_id])
end
end
コントローラのクラスやメソッドごとに変数利用の有無をbefore_action
で意識する必要がないし、book
はcurrent_user
に依存するが記述の順番を意識しなくてよい。
メソッドにしておくとシンプルに書くことができて良い。