Our Daily Method #8: Object.alias_class_method

Geplaatst door Remco van 't Veer do, 14 feb 2008 08:00:00 GMT

In an earlier daily method an alias is created for a class method. This is a bit tricky since the Module#alias_method method only operates in instance methodes. Fortunately a class is an instance of Class so we can use that instance as a context to use alias_method.

To extend an object instance we use the class<< notation. This adds a singleton/eigen/virtual/meta-class to the given instance which you can use to add methodes. Inside a class definition the self object points to the instance of the class begin defined. This allows us the do the following:


class Foo
  class << self
    alias_method :neu, :new
  end
end

This Foo class can now be instanciated using neu (note, new is just a class method). But this class<< stuff inside a class is a bit messy. I prefer using the following extension to Object:


class Object
  def self.alias_class_method(new_name, old_name)
    meta = class << self; self; end
    meta.send :alias_method, new_name, old_name
  end
end

Now we can write:


class Foo
  alias_class_method :neu, :new
end

For more information about eigenclasses see the discussion Nutter and Lam had on Ruby-core.

Geplaatst in , ,  | geen reacties

Reacties

(Laat url/e-mail achter »)

   Voorvertoning