A memo on how to define common variables in Rails 5 controllers.
There are several ways to define common variables across controllers or the entire app in Rails applications. Here’s a summary of these methods and related information.
-
Defining in ApplicationController:
class ApplicationController < ActionController::Base HASH_DATA = { value: "key" } endThis method defines a constant available to all controllers and actions. The constant
HASH_DATAis shared across the entire application. -
Using
before_actionwithin a controller:class SomeController < ApplicationController before_action :set_admin def set_admin @listOfWords = ['a', 'b', 'c'] end endThis method uses
before_actionto define a common variable (in this case@listOfWords) within a specific controller. This variable is accessible from all actions in the controller. -
Defining a method in ApplicationController:
class ApplicationController < ActionController::Base def common_variable @listOfWords = ['a', 'b', 'c'] end endThis method adds a method to
ApplicationController, and you can set common variables by calling this method in controllers. This is a flexible way to define variables, and you can call thecommon_variablemethod in controllers as needed.
The choice among these methods can be made flexibly according to your application’s requirements. Variables need to be defined as instance variables (@variable). Such variables are accessible in views, making them convenient for passing data from controllers to views.