I know there are religious wars fought over part of what I'm about to ask. I'm not here for any of that. I'm just curious why in my rails application helper I cannot have a global level variable honored.
Should I be able to do something like this:
module ApplicationHelper
magic_variable = HashWithIndifferentAccess.new(
{
blah: "primary",
blah_blah: "secondary",
})
def random_help
# do something cool with magic_variable?
end
end
I know there are religious wars fought over part of what I'm about to ask. I'm not here for any of that. I'm just curious why in my rails application helper I cannot have a global level variable honored.
Should I be able to do something like this:
module ApplicationHelper
magic_variable = HashWithIndifferentAccess.new(
{
blah: "primary",
blah_blah: "secondary",
})
def random_help
# do something cool with magic_variable?
end
end
Share
Improve this question
edited Mar 20 at 1:51
mechnicov
15.8k5 gold badges46 silver badges67 bronze badges
asked Mar 19 at 23:16
Michael K MadisonMichael K Madison
2,1193 gold badges22 silver badges36 bronze badges
2
|
2 Answers
Reset to default 7TLDR: It's not global variable, it's local variable and you try to use it out its scope
It's even not instance variable, not class variable, and not constant
Variables defined like your magic_variable
inside a module or a class are local to that scope but are not available inside methods etc.
From the docs
Generally, the scope of a local variable is one of
proc{
...}
loop{
...}
def
...end
class
...end
module
...end
the entire program (unless one of the above applies)
You can use:
- a global variable (
$magic_variable
) - an instance variable (
@magic_variable
) - a class variable (
@@magic_variable
) - a constant (
MAGIC_VARIABLE
)
And probably only last one is good by semantics for your situation
module ApplicationHelper
CONSTANT = {
blah: "primary",
blah_blah: "secondary",
}.with_indifferent_access.freeze
def random_help
# do something cool with CONSTANT
end
end
Constants are public by default, so you can also use ApplicationHelper::CONSTANT
somewhere outside that module
It doesn't have anything to do with the ApplicationHelper
or Rails, it is just Ruby's scoping rules.
If you go into a rails console
or preferably just a plain 'ol irb
console, you can play around with this:
$ irb
some_var = "foo"
def some_method
puts some_var
end
some_method # call the method
This will raise an exception:
undefined local variable or method `some_var' for main (NameError)
If you want that accessible in all helpers, just wrap it in a method:
def magic_variable
HashWithIndifferentAccess.new({ blah: "primary", blah_blah: "secondary" })
end
This won't let you mutate/change it, though. You'll need to store it in an instance variable or wrap it in a class that enables you to set it.
$
. ruby-doc./docs/ruby-doc-bundle/UsersGuide/rg/globalvars.html – max Commented Mar 20 at 11:56