Steve B.
Steve B.

Reputation: 57284

referring to module level variables from within module

I'm having some difficulty with referring to module-level variables in ruby. Say I have a situation like this, where I'm referring to M.a internally:

module M
  @@a=1

  def self.a
    @@a
  end

  class A
    def x
      M.a
   end
  end
end

Now, this example works fine for me but it is failing in a slightly more complicated context (where the module is spread over a number of files installed in a local gem - but my understanding is that that should not effect the way the code is executed) with an error like this: undefined method `a' for M::M (NoMethodError).

So, is this the correct way to refer to module level variables in context? is there a simpler/more idiomatic way?

Upvotes: 1

Views: 1532

Answers (1)

tadman
tadman

Reputation: 211560

If the module is spread out over other files, you need to ensure that your initialization is run before the method is called. If they are in the same file, this should be as much as guaranteed, but if you somehow split them there could be trouble.

I've found you can usually get away with this:

module M
  def self.a
    @a ||= 1
  end
end

If this variable is subject to change, you will need a mutator method. Rails provides mattr_accessor that basically does what you want, part of ActiveSupport.

Upvotes: 4

Related Questions