Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pundit policies more DRY?

In one of my project I started to using pundit gem and I have a very simply policy that looks like this:

class CompanyPolicy < ApplicationPolicy
  def index?
    true if user.is_a? Administrator
  end

  def new?
    true if user.is_a? Administrator
  end

  def create?
    new?
  end

  def edit?
    true if user.is_a? Administrator
  end

  def update?
    edit?
  end
end

And the question is how can I avoid repeating this:

true if user.is_a? Administrator
like image 891
Mateusz Urbański Avatar asked Oct 19 '25 15:10

Mateusz Urbański


1 Answers

I do trick which looks like this:

class ApplicationPolicy

  private

  def self.permit_owner_to(*actions)
    actions.each do |action|
      define_method("#{action}?") do
        owner?
      end
    end
  end

  def owner?
    # owner logic
  end

end

And used it in other policies

class ItemPolicy < ApplicationPolicy

  permit_owner_to :show, :update, :destroy, :confirm

end
like image 97
Sebastian Avatar answered Oct 22 '25 07:10

Sebastian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!