Meta Programming
Meta Programming
Mayuri Pachpande
Software Developer
Neosoft Technologies
Ruby Features:
1. Object-Oriented
2. DRY
3. Metaprogramming
What is Metaprogramming?
Code that writes code
Metaprogramming is the writing of computer programs with the ability to treat programs as their data.
It means that a program could be designed to read, generate, analyze, or transform other programs
and even modify itself while running.
Aspects of Metaprogramming
1. Introspection
2. Sending Messages
3. Classes are always open
4. Dynamic Methods
Introspection
Introspection - Ask questions about or look inward
In ruby, we can ask questions to our code during runtime: Some methods are as
listed below:
1. respond_to?
2. ancestors
3. instance_variables
4. Methods
5. inspect
Sending Messages
We often invoke a method on an object in Ruby
“Ruby on Rails”.upcase
1. The string “Ruby on Rails” is the object which will receive the message.
2. The dot (‘.’) tells the string object that we will be sending some message.
3. ‘Upcase’ is the message.
Sending Messages
Types of dynamic method calls:
1. send
2. method().call
3. eval
instance_eval
class_eval
1. String / Symbol
2. Block
Dynamic Methods
When a particular method is not defined, ruby invokes ‘method_missing’ method
We can define this method in our class to define the required methods
dynamically.
1. Method name
2. Arguments
3. Block
remove_method & undef_method
To remove existing methods
https://www.sitepoint.com/ruby-metaprogramming-part-ii/
https://www.toptal.com/ruby/ruby-metaprogramming-cooler-than-it-sounds
https://blog.codeship.com/metaprogramming-in-ruby/