Class: Dry::Ability::ControllerResource

Inherits:
Dry::Ability::Controller::Resource show all
Defined in:
lib/dry/ability/controller_resource.rb

Overview

Handle the load and authorization controller logic so we don’t clutter up all controllers with non-interface methods. This class is used internally, so you do not need to call methods directly on it.

Instance Method Summary collapse

Methods inherited from Dry::Ability::Controller::Resource

#assign_attributes, #authorization_action, #authorize_resource, #call, #collection_instance, #collection_instance=, #current_ability, #id_param, #initial_attributes, #load_and_authorize_resource, #load_collection, #load_instance?, #load_resource, #parameters_require_sanitizing?, #params_method, #parent?, #parent_name, #parent_resource, #resource_class, #resource_class_with_parent, #resource_instance, #resource_instance=, #resource_params, #resource_params_by_namespaced_name, #skip?

Instance Method Details

#build_resourceObject



19
20
21
22
# File 'lib/dry/ability/controller_resource.rb', line 19

def build_resource
  resource = resource_base.new(resource_params || {})
  assign_attributes(resource)
end

#find_resourceObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/dry/ability/controller_resource.rb', line 24

def find_resource
  if singleton? && parent_resource.respond_to?(name)
    parent_resource.public_send(name)
  elsif find_by.present?
    if resource_base.respond_to? find_by
      resource_base.public_send(find_by, id_param)
    else
      resource_base.find_by(find_by => id_param)
    end
  else
    resource_base.find(id_param)
  end
end

#load_resource_instanceObject



11
12
13
14
15
16
17
# File 'lib/dry/ability/controller_resource.rb', line 11

def load_resource_instance
  if !parent? && @mediator.new_actions.include?(@action_name)
    build_resource
  elsif @mediator.id_param_key || @mediator.singleton?
    find_resource
  end
end

#resource_baseObject

The object that methods (such as “find”, “new” or “build”) are called on. If the :through option is passed it will go through an association on that instance. If the :shallow option is passed it will use the resource_class if there’s no parent If the :singleton option is passed it won’t use the association because it needs to be handled later.



42
43
44
45
46
47
48
# File 'lib/dry/ability/controller_resource.rb', line 42

def resource_base
  if @mediator.through
    resource_base_through
  else
    resource_class
  end
end

#resource_base_throughObject



50
51
52
53
54
55
56
57
58
59
# File 'lib/dry/ability/controller_resource.rb', line 50

def resource_base_through
  if parent_resource
    @mediator.singleton? ? resource_class : parent_resource.public_send(@mediator.through_association)
  elsif @mediator.shallow?
    resource_class
  else
    # maybe this should be a record not found error instead?
    raise AccessDenied.new(nil, authorization_action, resource_class)
  end
end