Class: CanCan::ControllerResource

Inherits:
Object
  • Object
show all
Includes:
ControllerResourceLoader
Defined in:
lib/cancan/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.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ControllerResourceLoader

#load_resource

Constructor Details

#initialize(controller, *args) ⇒ ControllerResource

Returns a new instance of ControllerResource.



25
26
27
28
29
30
# File 'lib/cancan/controller_resource.rb', line 25

def initialize(controller, *args)
  @controller = controller
  @params = controller.params
  @options = args.extract_options!
  @name = args.first
end

Class Method Details

.add_before_action(controller_class, method, *args) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/cancan/controller_resource.rb', line 11

def self.add_before_action(controller_class, method, *args)
  options = args.extract_options!
  resource_name = args.first
  before_action_method = before_callback_name(options)
  controller_class.send(before_action_method, options.slice(:only, :except, :if, :unless)) do |controller|
    controller.class.cancan_resource_class
              .new(controller, resource_name, options.except(:only, :except, :if, :unless)).send(method)
  end
end

.before_callback_name(options) ⇒ Object



21
22
23
# File 'lib/cancan/controller_resource.rb', line 21

def self.before_callback_name(options)
  options.delete(:prepend) ? :prepend_before_action : :before_action
end

Instance Method Details

#authorize_resourceObject



37
38
39
40
41
# File 'lib/cancan/controller_resource.rb', line 37

def authorize_resource
  return if skip?(:authorize)

  @controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
end

#load_and_authorize_resourceObject



32
33
34
35
# File 'lib/cancan/controller_resource.rb', line 32

def load_and_authorize_resource
  load_resource
  authorize_resource
end

#parent?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/cancan/controller_resource.rb', line 43

def parent?
  @options.key?(:parent) ? @options[:parent] : @name && @name != name_from_controller.to_sym
end

#skip?(behavior) ⇒ Boolean

Returns:

  • (Boolean)


47
48
49
50
51
52
53
# File 'lib/cancan/controller_resource.rb', line 47

def skip?(behavior)
  return false unless (options = @controller.class.cancan_skipper[behavior][@name])

  options == {} ||
    options[:except] && !action_exists_in?(options[:except]) ||
    action_exists_in?(options[:only])
end