Namespacing and variables

I’m new to Ruby.

I hear modules can be used similar to namespaces.

I want to place a variable (value does vary so not a constant) inside a “namespace” and have it accessible from outside.

Searching, I find there’s a few different ways.

  1. cattr_accessor - I can’t yet figure out how to install or use this properly and I’m not using rails. (require fails with “cannot load such file – facets/module/cattr” although facets is installed and just “facets” loads).

  2. getters and setters. These require far too much code to set up, and the setter examples I see seem to only set the = operator, so I can’t use += etc.

What is the least verbose way to let me do something like

module Foo
	@@x = 5;
end

Foo.x = 6;
puts Foo.x; # 6

It doesn’t have to use module, I just want namespacing.

Thanks.

Modules are namespaces for methods and constants, so you can do

module Foo 
  X = 1
end

You will get warnings if you try to change the constant (though you still can).

2.7.0 :053 > Foo::X
=> 1
2.7.0 :054 > Foo::X += 2
(irb):54: warning: already initialized constant Foo::X
(irb):51: warning: previous definition of X was here
2.7.0 :055 > Foo::X
=> 3

There is also:

module Foo
  class << self
    attr_accessor :y  # this creates get/set methods for you
  end
end

2.7.0 :062 > Foo::y=2
2.7.0 :063 > Foo::y
=> 2
2.7.0 :064 > Foo::y += 1
2.7.0 :065 > Foo::y
=> 3

1 Like

Thanks for the reply.

I don’t really get the reasoning here (for why it’s so complex) - is ruby actually trying to discourage public static (to use c terminology) variables? is it an oversight or legacy issue? do most people not use namespaces? do people just not use stuff like this often in ruby? or something else?

Would people like, say, being allowed to use the public keyword to modify a variable’s scope?


[SOLVED]: I managed to get mattr_accessor working, just needed a more recent ruby (2.7.1) than the current ubuntu package (2.5) plus the accessor_extender gem.