I am currently experimenting with Ruby and Rails, and I’ve hit a few sections in tutorials and books about metaprogramming. Many mention that it is an essential component of Ruby but they don’t really go into detail. It’s as if metaprogramming is the final frontier for Ruby programmers. Coming from a .NET background I am struggling to understand why it is supposedly so useful.
- What benefits are gained when using metaprogramming?
- What is an eigenclass and how is it different from a singleton?
- In what situations is using metaprogramming common?
- What ethical implications are there around using code to modify the behaviour of other code, especially code which is not your own?
What benefits are gained when using metaprogramming?
You can create more expressive APIs than without it (for example ActiveRecord uses metaprogramming to define accessor methods based on a table’s column names, so you can write things like
person.ageinstead of something likeperson.read_attribute("age"), wherepersonis an active record object and thepeopletable has a column calledage) and you can accomplish some things with significantly less code than you otherwise would.What is an eigenclass and how is it different from a singleton?
The terms “eigenclass” and “singleton class” are used interchangeably in the context of ruby.
In what situations is using metaprogramming common?
In situations where you’d otherwise have a lot of boiler plate code or when creating DSLs.
Example of use case 1:
Instead of writing something boiler-plate code like this:
You can write this much shorter code using the metaprogramming method
attr_accessor, which automatically defines getter and setter methods with names based on the arguments you give it:If
attr_accessordidn’t already exist in the standard library, you could define it yourself like this (to give you an idea what metaprogramming in ruby looks like):end
What ethical implications are there around using code to modify the behaviour of other code, especially code which is not your own?
None.