cancan 里的 load_and_authorize_resourceend

使用

class BooksController < ApplicationController
  load_and_authorize_resourceend
end

对应

14
15
16
# File 'lib/cancan/controller_additions.rb', line 14

def load_and_authorize_resource(*args)
  cancan_resource_class.add_before_filter(self, :load_and_authorize_resource, *args)
end

这是对应

# File 'lib/cancan/controller_resource.rb', line 24
def load_and_authorize_resource
  load_resource
  authorize_resource
end

分为两部分:

一,

# File 'lib/cancan/controller_resource.rb', line 29

def load_resource
  unless skip?(:load)
    if load_instance?
      self.resource_instance ||= load_resource_instance
    elsif load_collection?
      self.collection_instance ||= load_collection
    end
  end
end

这又再次为分两部分:

# File 'lib/cancan/inherited_resource.rb', line 4

def load_resource_instance
  if parent?
    @controller.send :association_chain
    @controller.instance_variable_get("@#{instance_name}")
  elsif new_actions.include? @params[:action].to_sym
    resource = @controller.send :build_resource
    assign_attributes(resource)
  else
    @controller.send :resource
  end
end

def load_collection                                                 

  resource_base.accessible_by(current_ability, authorization_action)

end        


def current_ability

  @controller.send(:current_ability)

end


def authorization_action

  parent? ? :show : @params[:action].to_sym

end

---------

  • - (Object) accessible_by(ability, action = :index)

    Returns a scope which fetches only the records that the passed ability can perform a given action on.

@articles = Article.accessible_by(current_ability)
@articles = Article.accessible_by(current_ability, :update)

                                                         

另一部分:

# File 'lib/cancan/controller_resource.rb', line 39

def authorize_resource
  unless skip?(:authorize)
    @controller.authorize!(authorization_action, resource_instance || resource_class_with_parent)
  end
end





你可能感兴趣的:(cancan 里的 load_and_authorize_resourceend)