From: Gennady Bystritsky Date: 2012-05-28T01:54:11+09:00 Subject: Re: Am I justified to use a global variable if it must be used in all scopes? On May 27, 2012, at 5:33 AM, Phil Stone wrote: > Hello, > Ever since I started learning Ruby, I've been strongly discouraged > from using global variables > (http://www.caliban.org/ruby/rubyguide.shtml#style) > (http://www.ruby-forum.com/topic/187685#819233). > > In a program I'm making, I have a variable (which stores an instance of > a class) that is declared outside of any functions or classes. However, > I need to be able to call its methods from various class and function > scopes, and nothing but a global variable would let me do that. This > variable is simply what the program is centered around, and must be > accessed and edited by various classes. I'm not sure why a global > variable would be such a bad habit in this case, especially since it is > only one. > > Can I justify using it? Avoid using globals as much as possible, variables or constants alike. The are very hard to look for where they are coming from, impossible to mock and painful while unit testing in general as they keep persistent state not being reset for individual test cases. There are many alternatives to using globals, depending on your particular case. The best would be to design your app in a way that an instance can request what it needs from some other instance, possibly made available at instantiation (or via dependency injection). As others suggested, you can use a singleton for a class that provides state for the whole app, which I personally dislike. Or just class methods. This is what I sometimes use when I need a quick and dirty way to do the job, to be refactored at the earliest opportunity: === main script class App def start ... end def self.config @config ||= Config.new end end App.new.start === end of main script === player.rb class Player def config App::config end def perform return if config.idle_mode? ... end end === end of player.rb While behaving exactly as a global config would, it makes it possible to mock config on several levels in your unit tests. Besides, you can clearly see where the data is coming from. Hope this makes sense to you, Gennady. > > -- > Posted via http://www.ruby-forum.com/. >