2014年7月4日金曜日

Punditでsessionとかにアクセスしてみるヘ(^o^)ノ

CanCanあかんみたい。なので。。。

Punditを使ってみました。

シンプルで良くできたgemだと思います。

とりあえずインストール
$ rails g pundit:install

するとapp/policies/application_policy.rbが作成されます。

authorizeはアクセス制御

index?とかupdate?とかにロジックを書けばよし

コントローラにコレ書いて
rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

プライベートメソッドでどっかにredirectすれはおk
def user_not_authorized
  # errorメッセージ
  flash[:error] = "You are not authorized to perform this action."
  
  # リダイレクト先
  redirect_to(request.referrer || root_path)
end

AppicationPolicyクラス内でセッション情報にアクセスしたい!

application_controller.rb
before_action :_current_session

protected def _current_session
  accessor = instance_variable_get(:@_request)
  ApplicationPolicy.send(:define_method, :session, ->{accessor.session})
end

パラメータもいけまっせー
ApplicationPolicy.send(:define_method, :params, ->{accessor.params})

( ̄(エ) ̄)彡☆


参考
rails 4 対応の認可の gem