New to Rails: how do you use application_controller.rb in your rails application?

I just get on the rails and start to understand it slowly. Can someone explain or give me ideas on the benefits or when and why for coding inside application_controller? What are some of them. How do you use the application controller for your rails application? I don’t want to enter too much code, because from what I understand, this controller is called for every request. It's true?

+4
source share
2 answers

ApplicationController is practically the class that any other controller in your application inherits from (although this is not necessary in any case).

I agree not to spoil it with too much code and keep it clean and tidy, although there are some cases where ApplicationController will be a good place to put your code. For example: if you work with several language files and want to set the locale based on the requested URL, do this in your ApplicationController:

before_filter :set_locale def set_locale I18n.locale = params[:locale] || I18n.default_locale end 

This will save you from a headache when setting up the language in each controller separately. You do this once, and you have a locale installed throughout the system.

The same can be said for the famous protect_from_forgery , which can be found in the default ApplicationController for the new rails application.

Another use case can save all exceptions of a certain type in your application:

 rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found private def record_not_found  render :text => "404 Not Found", :status => 404 end 

In general, if you have a feature that all other controllers will definitely use, the ApplicationController may be a good place for it.

+7
source

I use it for helpers and methods that need to be used in multiple controllers. A good example is Ryan Bates "Super Simple Authentication from the Ground Up"

 class ApplicationController < ActionController::Base protect_from_forgery helper_method :admin? protected def authorize unless admin? flash[:error] = 'Sorry, that page is only for admins' redirect_to :root false end end def admin? session[:password] == "password" end end 

Then you can use all before_filter :authorize or if admin? from anywhere in your application.

0
source

Source: https://habr.com/ru/post/1441051/


All Articles