Confusion between callbacks in controller?

265 views Asked by At

My controller class has two before callbacks one from gem cancancan and other from within rails as:

load_and_authorize_resource  
before_action :set_company, only: [:show, :edit, :update, :destroy]  

Now my questions are:
1) Is the order correct for these callbacks ?

2) How 'load_and_authorize_resource' loads instance variables (means what's name of instance variable ? What if I would like to give a custom name for instance variable ?

3) In the above callback, does second one overrides the loaded instance variables of load_and_authorize_resource or creates its own set, what happens if we give custom name for instance variable. (say "@com=Company.find(params[:id])" instead of "@company=Company.find(params[:id])").

Sorry !!! if question doesn't make sense, I'm new to rails. Hoping your answers will let me better understand this question. Happy Coding.

1

There are 1 answers

1
dreamingblackcat On BEST ANSWER

May be it's a good time to look into internals of a gem. CanCanCan (formerly CanCan) has a lot of magic. So, it's hard to understand in detail without looking at the code. To answer your questions:

(1). CanCanCan adds it's method as before_filter(which means append at the end of chain) if you don't add a prepend: true option. before_filters are added in the order they are declared. So, with your code, cancancan's before filter will run before your :set_company. However, in this context, :set_company is not needed anymore because CanCanCan's load_resource method will do the same thing.

(2) load_and_authorize_resource has two parts. load_resource and authorize_resource which you can also use separately. load_resource automagically figures out the model and instance variable name from the controller name. So, in CompaniesController, it will run @company ||= Company.find(params[:id]). If you want to customize, you can supply options such asclass,instance_name`.

(3) This question is almost already answered. Yes, it will overwrite the instance variable if you keep the :set_company before_filter.

Below are the two source files concerned. It's very readable. Go ahead and read it. You are gonna understand the internals of CanCanCan better, hopefully.

controller_additions.rb controller_resource.rb