From: Gennady Bystritsky Date: 2012-05-29T01:44:45+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 3:06 PM, Phil Stone wrote: >> Name the class whatever you like. I think 'Jonan' would be an excellent >> name, but you might choose a name that more accurately describes its >> purpose. > I just wanted to give you an idea of what the program is supposed to do. > > @Gennady Bystritsky: > The particulars of your example don't make total sense... what's the > point of having a class method that accesses an instance variable? > What's the effect? Please explain. [Referring to my code that you unfortunately cut from your reply] First of all, it is not a "regular" instance variable -- it is a class instance variable. A class itself is an object (an instance of class Class), which may have its own instance variables. They are very distinct from instance variables of a particular instance of that class. Then: An instance variable cannot be access directly from outside, only via a method. Unlike a global variable, a method can be refactored to add some more behavior later on if needed, or overridden in a subclass. The method as presented already demonstrates one possible benefit over just a global variable -- "lazy initialization". A config object will not be created until the very first invocation of the method. Besides, you can mock this method in your unit tests: require 'mocha' ... class PlayerTest < Test::Unit::TestCase def test_does_nothing_when_idle App.expects(:config).returns mock("config", :idle_mode? => true) ... end end > > For Config.new, were you thinking of a data structure like this one?: > http://mjijackson.com/2010/02/flexible-ruby-config-objects > > Unfortunately, the class Config is already defined in my Ruby version: > > irb(main):001:0> Config > (irb):1: Use RbConfig instead of obsolete and deprecated Config. It was just an example, first name that came to mind to demonstrate the concept. Define this class inside class App, and it becomes App::Config. Or call it MyGloriousAppState, whatever (hate that name, btw.) And how the class is defined is irrelevant for this discussion. > > -- > Posted via http://www.ruby-forum.com/. >