Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Created October 22, 2010 06:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjsingleton/640068 to your computer and use it in GitHub Desktop.
Save tjsingleton/640068 to your computer and use it in GitHub Desktop.
Using define method with an module

We have a widget that we want to extend

class Widget
end

so we open it and define_method

class Widget
  define_method :hello do
    puts "Hello!"
  end
end

Output:

ruby-1.9.2-p0 >   Widget.new.hello
Hello!

Later we want to extend it with something else from a module

module World
  def hello
    super
    puts "World!"
  end
end

Widget.send :include, World

Output:

ruby-1.9.2-p0 >   Widget.new.hello
Hello!

but it doesn't work. :(

It's better is to include a module w\ a defined method

class BetterWidget
  anon_module = Module.new do
    define_method :hello do
      puts "Hello!"
    end
  end

  include anon_module
end

BetterWidget.send :include, World

Output:

ruby-1.9.2-p0 > BetterWidget.new.hello
  Hello!
  World!
 => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment