Rails 5 controller common variables

Defining Common Variables in Rails 5 Controllers

A memo on how to define common variables in Rails 5 controllers. For constants, you can use the config method or write directly in ApplicationController, but it seems different for variables.

Shou Arisaka
2 min read
Oct 7, 2025

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.

  1. Defining in ApplicationController:

    class ApplicationController < ActionController::Base
      HASH_DATA = { value: "key" }
    end

    This method defines a constant available to all controllers and actions. The constant HASH_DATA is shared across the entire application.

  2. Using before_action within a controller:

    class SomeController < ApplicationController
      before_action :set_admin
    
      def set_admin
        @listOfWords = ['a', 'b', 'c']
      end
    end

    This method uses before_action to define a common variable (in this case @listOfWords) within a specific controller. This variable is accessible from all actions in the controller.

  3. Defining a method in ApplicationController:

    class ApplicationController < ActionController::Base
      def common_variable
        @listOfWords = ['a', 'b', 'c']
      end
    end

    This 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 the common_variable method 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.

Share this article

Shou Arisaka Oct 7, 2025

🔗 Copy Links