Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Class-Level Method Chaining Using extend instead of include/ClassMethod module (See related posts)

This post is in response to the example of method chaining given at My hovercraft is full of eels.

module ForeignKeyMigrations::Schema

  def self.extended(object)
    class << object
      alias_method :define_without_fk, :define unless method_defined?(:define_without_fk)
      alias_method :define, :define_with_fk
    end 
  end

  def define_with_fk
    ...
    define_without_fk(...)
    ...
  end

end

ActiveRecord::Schema.extend(ForeignKeyMigrations::Schema)


The code I used to test this technique, which is really the same thing with domain information removed:

module Foo
  def self.extended(object)
    class << object
      alias_method :to_s_without_foo, :to_s unless method_defined?(:to_s_without_foo)
      alias_method :to_s, :to_s_with_foo
    end 
  end

  def to_s_with_foo
    "#{to_s_without_foo} - got foo!"
  end

end

class X
end

X.extend(Foo)
puts X.to_s


Comments on this post

floehopper posts on Aug 25, 2006 at 21:13
You might find Mocha useful if you want to mock or stub class methods without affecting subsequent tests.

You need to create an account or log in to post comments to this site.


Click here to browse all 5146 code snippets

Related Posts