Calling Methods During Class Definition

April 17, 2008

One of the features I like most about Ruby is the ability to execute code during the definition of a class. Here's a simple example:

class Foo
  puts "hi"
end

A more useful example is that you can call a method and self is set to the class you are defining.

class Foo
  def self.whoami
    puts "You are #{self}"
  end
end
class Bar < Foo
  whoami
end

This prints You are Bar. This is a feature that isn't common to most languages, for example, you can't do it in PHP, Python(I don't think, Pythonistas jump in there if I'm wrong), Java or even Groovy. The reason why this kind of method is so helpful is this how you can write code that writes code. This is the closest thing Ruby has to Lisp macros. You see this used in Ruby in with the attr_accessor method and in Rails with many methods, belongs_to and has_many being the most obvious examples.

This allows you to define the metadata about a class in the most DSL-like syntax. It would be really great to see this kind of thing in Groovy.

Posted in Technology | Tags Python, Ruby, Java, PHP

Comments Disabled