Archive for the ‘Java’ Category

My favourite Ruby Gem is Magic

Tuesday, June 19th, 2007

On Ruby asks in June’s Blogging Contest:

“Other than Rails, what is your favorite Ruby Gem, and why?”

My favourite Ruby Gem is Dr Nics Magic Models.

Magic Models weaves a dark spell on your code that makes your ActiveRecord Models just disappear. It’s glorious for demonstrating to the skeptical the possibilites affored by Ruby, and it makes prototyping and development even more efficient. As Dr Nic says:

In a way, MM works like scaffolding does at the controller level - it lets you get your application “working” faster even though you’ll probably rewrite it in the end anyway.

Starting with Magic Models is a matter of installing the Gem and requiring it in your application:

gem install dr_nic_magic_models
require 'dr_nic_magic_models'

Now you have Models that appear based on your defined database tables, no other code required. So if you have a People Table, you automagically have a Person Model with attributes matching the columns defined in the table.

If you crack open the gem, you find the Magic isn’t so magic after all. The crucial action occurs in const_missing.

def const_missing(class_id)
  begin
    return normal_const_missing(class_id)
  rescue
  end
  @magic_schema ||= DrNicMagicModels::Schema.new self
  unless table_name = @magic_schema.models[class_id]
    raise NameError.new("uninitialized constant #{class_id}")
      if @magic_schema.models.enquired? class_id
  end
  superklass = @magic_schema.superklass || ActiveRecord::Base
  klass = create_class(class_id, superklass) do
    set_table_name table_name
    # include DrNicMagicModels::MagicModel
    # extend DrNicMagicModels::Validations
  end
  klass.generate_validations
  @magic_schema.inflector.post_class_creation klass
  klass
end

const_missing is called when the Ruby Interpreter cannot find a constant. In the example above, if we call the Person model (using Person.find, for example), const_missing is called and Magic Models goes into action - checking the database for a corresponding table and creating a class with the appropriate attributes and validations. The rest writes itself.

Magic Models looks like magic to those uninitiated in the wonders of a truly dynamic language.

I use them to get a leg-up on new development. I have also used them to demonstrate to some colleagues the things that are possible with Rails - scaffolding for free, testing baked-in, easy AJAX and code that isn’t there but works anyway.

It’s worth learning, just to see the expression on the PHP and Java guy’s faces.

If you’re looking for more: