Łukasz
Łukasz

Reputation: 102

How using in Ruby's attr_reader and attr_writer for variable @@?

Ruby has this way to share instance variables by using keys like

attr_accessor :v
attr_reader :v
attr_writer :v

How using this but for global @@variable object? Each class can uses variable shared with each instance of object. How creating acessor? Only proper way is

def zmienna=(a)
 @@zmienna = a
end

Upvotes: 1

Views: 117

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369546

There is no such thing in Ruby. But it is not that hard to write your own:

class Module
  def mattr_writer(*attrs)
    attrs.each do |attr|
      define_singleton_method(:"#{attr}=") do |val|
        class_variable_set(:"@@#{attr}", val)
      end
    end
  end

  def mattr_reader(*attrs)
    attrs.each do |attr|
      define_singleton_method(attr) do
        class_variable_get(:"@@#{attr}")
      end
    end
  end

  def mattr_accessor(*attrs)
    mattr_reader(*attrs)
    mattr_writer(*attrs)
  end
end

class Foo; end
Foo.mattr_accessor(:bar)
Foo.bar = 42

Foo.bar #=> 42

Foo.bar = 23

Foo.bar #=> 23

Or, you could use ActiveSupport, which already provides these methods.

However, since most style guides discourage usage of class hierarchy variables, there is not much point in having accessors for them.

Upvotes: 1

Related Questions