1

I need something like Scope inheritance in pundit. Imagine this scenarion:

class ApplicationPolicy
  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope.where(:company => user.companies)
    end
  end
end

Now, any policy inherited from ApplicationPolicy has a scope and I can use it through policy_scope. This is nice because I have few models belongs_to :company with exact same scoping rules.

But what if I need another scope for another policy? Ok:

class DeviceGroupPolicy < ApplicationPolicy
  class Scope
    attr_reader :user, :scope

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

    def resolve
      scope.joins(:devices).where("devices.company_id in (?)", user.companies.map{|c| c.id}).group("device_groups.title")
    end
  end
end

Notice that the only difference in this Scope class is in resolve method.

How can I reuse the same Scope class from ApplicationPolicy in other policies without copy-pasting this boilerplate code?

Oleg Antonyan
  • 2,943
  • 3
  • 28
  • 44
  • extend `ApplicationPolicy` class ``` class DeviceGroupPolicy < ApplicationPolicy def resolve scope.joins(:devices).where(devices: { company_id: @user.companies).group("device_groups.title") end end ``` – itsnikolay May 01 '15 at 16:25
  • Doesn't work. `resolve` method is declared inside nested `Scope` class, not `ApplicationPolicy` class itself – Oleg Antonyan May 02 '15 at 06:58

1 Answers1

0

You can do this:

class DeviceGroupPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      scope.joins(:devices).where("devices.company_id in (?)", user.companies.map{|c| c.id}).group("device_groups.title")
    end
  end
end

According to the documentation (the second code snippet), you can inherit the subclass as well.

nikkon226
  • 998
  • 6
  • 11