This is Part 3 in my series Retro-reading RailsSpace. Despite the book being slightly out of date, and geared toward beginners, it’s a classic. I’m reading it (finally) and posting what I learn.
First, I’m Cheating
I didn’t actually learn today’s migration mojo from RailsSpace directly. The book was more of an inspiration. I saw the old-school t.column call, and for the first time I wondered, “how does it work?”
When I started using Ruby on Rails, this was just magic. And I didn’t question it…
create_table :posts do |t| t.column :name, :string # poof, a string column # t.string :desc # poof, a string column with even shorter syntax # t.integer :views # poof, an integer column # end
So how does it work? The answer is the TableDefinition class we’ve been using. Don’t see it? It’s the t in t.column, t.string, and t.integer above. When we call create_table an instance of the TableDefinition class is created, and passed to the block (everything between do and end).
column is an instance method of TableDefinition, and adds the column definition to the TableDefinition class. t.string, t.integer, and others just call t.column on the backend.
I think it’s obvious why it was coded this way. Can you imagine a shorter, sweeter syntax? I experimented with lots of SQL shortcuts back in my Perl days, but nothing that worked this well. Blocks in general are a very cool aspect of Ruby, and Rails would lose a lot of its power without them.