I would like to declare a variable in my application_controller.rb controller that is accessible to all controllers that inherit from it. if possible I would like the variable only accessible in the child classes, nowhere else, including the views (unless specifically passed into the view).
I am new to Ruby and Rails and am unsure if the “protected” scope exists for variables, I have seen that it does for functions. I have not been able to find a simple answer and I have been experimenting a little in my app with different ways to declare variables and where they can be accessed. That has provided me with no information about how I can accomplish this.
Any help would be greatly appreciated.
Code:
class ApplicationController < ActionController::Base
protect_from_forgery
@admin_name = "AdminUserName"
@admin_password = "AdminPassword"
end
class ProjectsController < ApplicationController
http_basic_authenticate_with :name => @admin_name, :password => @admin_password, :except => [:index, :show]
# controller functions here
end
This does not seem to be working for me.
As you have recognized, something like a protected scope does not exist for variables in ruby. You can use an instance variable in Rails to set variables in controllers that are accessible to views. It’s an old Rails feature that you can use instance variables set in the controller in the views.
Instance variables get inherited from instance to instance
But be aware that by passing instance variables to views rails is breaking encapsulation and using it through all partials may not be good practice. Best of all, replace instance variables with local variables as soon as they land in the views
UPDATE
In your case, use constants. Constants are under the scope of the class they have been defined in and get inherited, but they are not available to the views unless called with scope
I guess you do not want to call them in the view. If you really wanted to do that, you can do it like this: