How can I declare a global variable in Ruby on Rails?
My sample code:
in my controller#application.rb
:
def user_clicked()
@current_userid = params[:user_id]
end
in my layout#application.html.haml
I have sidebar with this link:
= link_to "John", user_clicked_path(:user_id => 1)
= link_to "Doe", user_clicked_path(:user_id => 2)
= link_to "View clicked user", view_user_path
in my views#view_user.html.haml
:
%h2 @current_userid
I want to declare a global variable that can modify my controller and use it anywhere, like controller, views, and etc. The above is only a sample scenario. If I click the John or Doe link, it will send a user_id
to the controller and when I click the "View clicked user" link, it will display the last clicked link. It is either John=1
or Doe=2
.
Of course if I click the "View clicked user" link first, it will display nil
.
Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($).
The global Keyword Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function. To create a global variable inside a function, you can use the global keyword.
@title is an instance variable - and is available to all methods within the class. In Ruby on Rails - declaring your variables in your controller as instance variables ( @title ) makes them available to your view.
Global variables are defined outside a function, usually on top of the program. Global variables hold their values throughout the lifetime of your program and they can be accessed inside any of the functions defined for the program.
In Ruby global variables are declared by prefixing the identifier with $
$foo = 'bar'
Which you rarely see used for a number of reasons. And it's not really what you are looking for.
In Ruby instance variables are declared with @
:
class DemoController
def index
@some_variable = "dlroW olleH"
@some_variable = backwards
end
private
def backwards
@some_variable.reverse
end
end
Rails automatically passes the controller's instance variables to the view context.
# /app/views/demos/index.html.haml
%h1= @some_variable
Guess what it outputs and I'll give you a cookie.
In your example @global_variable
is nil since controller#sample_1
is not called - the request would go through controller#sample_2
.
def sample_2
@global_variable = "Hello World"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With