Wednesday, February 20, 2008

ActiveRecord & Ruby2Ruby: This Is Where The Magic Happens

People say that Rails is full of magic. Do you ever wonder where the magic happens?



Peeking behind the curtain and seeing what makes the so-called "magic" tick is easy.



I'm in a Rails app which has ActiveRecord User models, each of which has an association class specified:

belongs_to :choice

I install the gem, and then I call

Ruby2Ruby.translate(User)

And Ruby2Ruby returns the class, translated from an object in memory into Ruby code.

In terms of the methods I get back, there are several association-related methods, and one class method I defined when creating the class itself. Conspicuously absent are methods like find and save - that's because they live on ActiveRecord::Base, not User itself.

Unfortunately, when you call

puts Ruby2Ruby.translate(ActiveRecord::Base)

...things kind of blow up. The same is true for ActionController. For some reason, just as it can show you User but not ActiveRecord::Base, it can show you UsersController but not ActionController. Ruby2Ruby can apparently only reveal some of the magic you might want to see.

But it's still a handy trick. Many Rails plugins of the acts_as_foo family add methods to models, and you should be able to see those changes with Ruby2Ruby. It's a very useful way to shed some light on what actually happens inside Rails' "magic."