りゅうじの学習blog

学習したことをアウトプットしていきます。

Punditの使い方

Pundit は認可まわりの機能を作成するのに有効なGemです。

Punditセットアップ

#Gemfile

gem 'pundit'
#ターミナル

bundle install --path vendor/bundle

application_controllerinclude

#app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery
end

ジェネレータを使用してapplication_policy.rbを生成。

#ターミナル

rails g pundit:install

Policies

#app/policies/application_policy.rb

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end

  def scope
    Pundit.policy_scope!(user, record.class)
  end

  class Scope
    attr_reader :user, :scope

    def initialize(user, scope)
      @user = user
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

Punditクラスは、以下のことを前提としています。

  • クラスの最後にPolicyとつける
  • userはデフォルトでcurrent_userになる
  • Policyクラスはクエリメソッドを実装する。このメソッドはコントローラのアクションに割り当てられる
#どこかのpolicy.rb

def index?
  true
end

def show?
  false
end

def create?
  user.admin? || user.editor?
end

コントローラのアクション名 + ? のメソッドを定義し返り値が true なら許可false なら拒否になります。

user.admin? || user.editor? はこのアプリに管理者と編集者とライターがいたとして、管理者と編集者にはtrueとなりライターのみfalseとなります。

コントローラでの使い方

#どこかのコントローラ
 
def create
  authorize(Article)
end

def edit
  authorize(@article)
end 

最後に

読んでいただいた方、ありがとうございました。