The scope or lifetime of a variable is an important consideration when putting together your rails application. Here are some hints about the scoping of certain types of variables, objects, controllers and methods.
Local variables are those variables that exist inside of a method. The duration of life for these variables ends at the end of the method.
For example, from the console try this:
def method1
a = 99
end
=>
method1 => 99
a => NameError: undefined local variable or method `a' for main:Object
def method2
puts a
end
=>
method2 => NameError: undefined local variable or method `a' for main:Object
from (irb):15:in `method2'
from (irb):17
@ variables follow an instance of an object.
This means that when you create an object the instance variable would be created and would die when the object is destroyed.
For example, from the console, type:
<pre>
class TrialClass
def method1
@a = 99
end
def method2
@a = 50
end
end
object1 = TrialClass.new
object2 = TrialClass.new
object1.method1 => 99
object1.inspect => #<TrialClass:0×359f4e8 @a=99>
object2.method2 = > 50
object2.inspect => #<TrialClass:0×359f4e8 @a=50>
object1.inspect => #<TrialClass:0×359f4e9 @a=99>
@@ variables exist after their declaraion, forever.
This type of variable once declared will exist throughout the entire application. You would use these variables when you are
For example:
$ variables are like @@ variables without a class.
$ (pronounced ‘dollar-sign’) variables are different from @@ variables because they
For example:
(In addition, refer to the Pickaxe Book’s section on variable scope.)
When an instance variable is assigned in a method, it is available to the view. however, when the view is exited, the variable will disappear.
For example:
def edit
@product = Product.find(params[:id])
end
The @product instance variable would be available to the edit.rhtml view and only to the edit view.
(In addition, refer to the Pickaxe Book’s chapter on Classes and Objects)
COMMENTS: this seems more about scoping in Ruby than in Rails. What are the differences between development and production mode, with the reloading of classes wiping out class variables if the file is edited? Where should I place absolutely global (accessible in every template, controller, helper, and model) configuration constants for my app, environment.rb?
category: Understanding