14.8. Summary

Rails takes advantage of Ruby's features that enable metaprogramming, or changing the programming context at runtime. Like many languages, Ruby has a statement that enables you to evaluate an arbitrary string. Unlike many languages, Ruby allows you to choose the execution context for that string to be any block or object. The classes Object, Class, and Module all have interesting introspective methods that enable metaprogramming constructs.

Ruby classes are also instances of the class Class, which permits class objects to be treated just like any other Ruby object. In addition, every Ruby object has a slot for a singleton class that lets you add methods to any individual instance in the system. When that instance is itself a class, the instance method of the class becomes a class method of instances of that class.

Ruby also allows classes to be reopened for the purpose of adding new methods at any time. This permits some elegant code, but can cause problems if used incorrectly. Ruby's alias feature can mitigate some of the risks, as well as offer an easy way to decorate an existing method. Rails offers an alias chaining feature that simplifies a common-use case. These features used together give the Rails plugin system much of its power.

When a method name is not found in Ruby, a special hook method called method_missing is invoked. You can use it to provide flexible behavior based on parsing the method names that are requested. You can also add method definitions ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.