The Story of Bob, Metaprogrammer
Bob, a newcomer to Ruby, has a grand plan: he’ll write the biggest Internet social network ever for movie buffs. To do that, he needs a database of movies and movie reviews. Bob makes it a practice to write reusable code, so he decides to build a simple library to persist objects in the database.
Bob’s First Attempt
Bob’s library maps each class to a database table and each object to a record. When Bob creates an object or accesses its attributes, the object generates a string of SQL and sends it to the database. All this functionality is wrapped in a class:
| class Entity |
| attr_reader :table, :ident |
| |
| def initialize(table, ident) |
| @table = table |
| @ident = ident |
| Database.sql ... |
Get Metaprogramming Ruby 2 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.