cattr_accessor and mattr_accessor
Friday, July 3rd, 2009In ruby, there is no public variable. All variables in object are hidden encapsulated. To access objects’ variables, getter and setter methods are necessary. It may sound painful if I have to make all the getter/setter methods. But don’t worry. Ruby has a smart solution. attr_accessor.
attr_accessor :school attr_reader :student attr_writer :student
This is good. With a simple declaration, encapsulation is achieved. It is OK for instance variables, but what about class variables? Unfortunately, ruby core does not have the attr_xxx for class variables. However, It is not that difficult to implement.
class Class
def cattr_accessor(name)
class_eval <<-EOS
unless defined? @@#{name}
@@#{name} = nil
end
def self.#{name}
@@#{name}
end
def self.#{name}=(obj)
@@#{name} = obj
end
EOS
end
end
class Test
cattr_accessor :greet
end
Test.greet = "hello"
p Test.greet
ActiveSupport
There is a easier way if you set up your mind to use activesupport. Activesupport already implemented cattr_xxx and mattr_xxx serieses.
require "activesupport" class ClassTest cattr_accessor :greet end module ModuleTest mattr_accessor :greet end
cattr_xxx works for class variables, and mattr_xxx wors for module variables.