I would know how the load_and_authorize_resource
works inside.
I searched the github page Link and tried to undestand , but i didn't find nothing usefull. I only understand that load_and_authorize_resource
is like a before_filter and it loads (in some way) the ability that we have written in ability.rb
I would know better how this is possible. I mean, i don't want to study ALL the gem, but i want just to see how cancan load the ability of a resource in a controller and if the load_and_authorize_resource
is really a sort of before_filter.
disclaimer: for the sake of simplicity, I omit some calls to short inner methods intentionally. The full chain of calling can be obtained by following
load_and_authorize_resource
method definition and so forth.As stated in documentation,
load_and_authorize_resource
sets up abefore_filter
......which calls two methods:
load_resource
andauthorize_resource
.To get the idea of their behaviour we're going to look at both of them closely.
Based on
params
hash which was passed to your controller action,load_resource
makes a decision on whether it should obtain a new instance of a class (e.g.Post.new
) orfind
a particular instance based onparams[:id]
(e.g.Post.find(params[:id])
). That instance (or a collection of instances for actions likeindex
) is assigned to corresponding instance variable of your controller action.Later on,
authorize_resource
gets called. Its inner logics syntax should be familiar to you: checking abilities by hands looks just the same as what happens inside of this method. Basically you take aresource_instance
obtained at the previous step,params[:action]
which is the name of a current action, and check if particular action can be accessed for given object(s).As long as raising exceptions inside of
before_filter
stops controller action from being executed, failing to pass authorization here gets you redirected to your application's home url, shown 500 error page or whatever behaviour you defined forCanCan::AccessDenied
handling.On the other hand, in case you've passed authorization successfully, your action code gets executed. Now you've got access to instance variable (e.g.
@post
) which has been set up byCanCan
atload_resource
step.