How Metaprogramming in Ruby works
Ruby has built in support for generating code when you need it. Sometimes you may run into situations of writing too much repetitive code in Ruby. If you want to programmatically define your methods for instance you can use two officially recognized ways of accomplishing it.
You can use define_method to create a method which can utilize location variables as defined at the time of method auto declarations. There are several decorators such as attr_reader that relies on this capability of metaprogramming. The nice feature of this metaprogramming is that Ruby will include this auto generated method in RDoc documentation for you.
However, define_method has several shortcoming including a lack of support for defining a method that takes a block.
Another approach to metaprogramming is to utilize module_eval method and convert string into methods. This feature is not unique to Ruby, but all other language highly regard this capability as dangers unlike Ruby, which embraces it.
Here is a list of metaprogramming examples for your reference.
class MyClass
def my_method
put “Hello”
end
end //standard way
class MyClass
define_method(‘my_method’) do
put “Hello”
end
end //using metaprogramming define_method approach
class MyClass
module_eval %{def my_method
put “Hello”
end}
end //using metaprogramming module_eval approach
String.module_eval %{def my_method
put “Hello”
end}
//using metaprogramming module_eval approach
Ruby develooer , in addition to creating methods via metaprogramming, can remove methods from classes. In order to accomplish this, Ruby provides remove_method method.
class MyClass
remove_method(:my_method)
end
Removal of a method is allowed only for methods defined within a scope of a class. Methods cannot be removed if they are inherited from superclass or a module. In order to stop a method from responding, you’ll need to use
class MyClass
undef_method(:my_method)
end