Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a global variable to all the controllers in Rails

I have a base URL common to all my controllers. I want to declare this as a variable in one place, and use it in all my controllers. That will make any future updates fast and simple. Is that possible? I'm declaring it in all my controllers like this:

@baseURL = "www.url.com/something/"
like image 342
Eduardo Pedroso Avatar asked Dec 03 '22 15:12

Eduardo Pedroso


2 Answers

In your application controller.

before_action :set_variables

def set_variables
 @baseURL = "www.url.com/something/"
end

This @baseURL instance variable will be accessible in all your actions and views as you make all controllers inherit the ApplicationController.

like image 58
Alok Swain Avatar answered Dec 05 '22 03:12

Alok Swain


Take advantage of ruby's inheritance chain. You can define that on some parent class of all your controllers as a constant, normally ApplicationController:

class ApplicationController < ActionController::Base
  BASE_URL = "www.url.com/something/"
end

Then it will become available to all is children, namely PostsController < ApplicationController.

like image 27
ichigolas Avatar answered Dec 05 '22 05:12

ichigolas