class ApiPresenter::Resolvers::PoliciesResolver

Attributes

presenter[R]
resolved_policies[R]

Public Class Methods

new(presenter) click to toggle source

Optimally resolves designated policies for current_user and supplied records.

Use where it is desirable for an API response to include permissions (policy) metadata so that a client can correctly present resource actions.

Initialize and preload policy associations for the given relation

@param presenter [ApiPresenter::Base]

Calls superclass method ApiPresenter::Resolvers::Base::new
# File lib/api_presenter/resolvers/policies_resolver.rb, line 17
def initialize(presenter)
  super(presenter)
  preload if relation.is_a?(ActiveRecord::Relation) && policy_associations.present?
end

Public Instance Methods

call() click to toggle source

Resolves policies and combines them into an id-based hash

@return [PolicyPresenter::Base]

# File lib/api_presenter/resolvers/policies_resolver.rb, line 26
def call
  resolve_policies
  self
end

Private Instance Methods

id_attribute() click to toggle source

@example Post -> “post_id”

@return [String]

# File lib/api_presenter/resolvers/policies_resolver.rb, line 54
def id_attribute
  @id_attribute ||= begin
    klass = if relation.is_a?(ActiveRecord::Relation)
      relation.klass
    else
      relation.first.class
    end
    "#{klass.base_class.name.underscore}_id"
  end
end
preload() click to toggle source

Preload any associations required to optimize policy methods that traverse models

# File lib/api_presenter/resolvers/policies_resolver.rb, line 34
def preload
  presenter.preload(policy_associations)
end
resolve_policies() click to toggle source

Run policies for each record in the relation

# File lib/api_presenter/resolvers/policies_resolver.rb, line 39
def resolve_policies
  @resolved_policies = relation.map do |record|
    policy_definition = Pundit.policy(current_user, record)
    record_policies = { :"#{id_attribute}" => record.id }
    Array.wrap(policy_methods).each do |policy_method|
      record_policies[policy_method] = policy_definition.send("#{policy_method}?")
    end
    record_policies
  end
end