Ruby is a dynamic language that allows us to do great things at runtime. Today, we are going to see how we can use metaprogramming to add methods to an object after it has been created.
Let us create a method
my_attr_accessor which mimics Ruby's built in
attr_accessor is used to dynamically create getters and setters for the fields of a class.
We will need to define
my_attr_accessor in - please pay attention, this may be confusing - the class
Class as an instance method. This makes
my_attr_accessor available in all classes as a class methed.
It does nothing at the moment, so we expect
NoMethodError to be thrown if we try to use the getter and setter for
To be able to run the specs that are present in each of the file snippets below, please make sure that you have
rspec gem installed. To run, use the command
To create a getter and a setter, we are going to use ruby's
Object#define_method. This method allows us to add a method definition dynamically, at runtime, to our object.
Now that we have the method definitions in place, we will need to add the actual implementation for accessing and modifying each of the attributes in order to get the specs to pass. For this, we seek the help of
Object#instance_variable_get allows us to access the instance variables by just sending a string-name of the variable as an argument to it.
Object#instance_variable_set allows us to modify the existing value of the instance variable by sending a string-name of the variable and the value to which it has to be modified.
And there you have it. A hand-rolled implementation of