Paul
Groves
Ltd

Class macros

Getting to grips with some of the basics of Ruby metaprogramming will help get rid of any sense of magic, and lead to the way to harnessing the power and simplicity of the language.

This example of a class macro demonstrates how simply Ruby's own attr_accessor getter/setter shortcut could be implemented:

class MyClass

  def self.my_attr_accessor(accessor_name)
    define_method(accessor_name) do
      instance_variable_get(:@accessor_name)
    end

    define_method("#{accessor_name}=") do |value|
      instance_variable_set(:@accessor_name, value)
    end
  end

  my_attr_accessor :example_attribute

end

test = MyClass.new
test.example_attribute = "this is my example value"

puts test.example_attribute