But it's generally considered good form to not use global variables in
the first place. There's almost always a way to avoid using them. The
danger of using them is that if you use a global variable with your
code, and someone else uses a global variable of the same name in their
code, the two bits of code will both break if they are ever run
together.
Raul: I believe it would also be bad form to hit the database
unnecessarily with every pageview. If It's bad form to cache data in a
variable that is visible to every page, then I don't want to be good
But in that case you're writing a real Sinatra application not a toy
Is there a "better" way to do this than @@? Why do constants have
different scopes than regular variables?
You can write your example as:
module Play
class Application < Sinatra::Base
vara = "foo"
VARB = "bar"
helpers do
def geta
vara
end
def getb
VARB
end
end
get '/a' do geta end
get '/b' do getb end
end
end
This should make thing a lot clearer as to what's going on, especially regarding scopes since it now looks more like actual Ruby code.
The constant VARB is really Play::Application::VARB in this case. If you want VARB global then you refer to it as ::VARB (everywhere)
In normal Ruby code what and where is vara in this case?
If you use @@vara it'll work, since vara will become a class variable of Play::Application
The trouble with that is that there's only one @@vara and it'll be used for all requests by all users. I'm also thinking that you probably don't really want that. If you don't then you'll have to keep vara someplace else, and look for it in each request.
Cheers,
Bob
···
On 27-Feb-10, at 10:25 PM, Nick Brown wrote:
--
Posted via http://www.ruby-forum.com/\.
----
Bob Hutchison
Recursive Design Inc.
http://www.recursive.ca/
weblog: http://xampl.com/so