Skip to content

Instantly share code, notes, and snippets.

@rf-
Created August 15, 2011 20:13
Show Gist options
  • Save rf-/1147702 to your computer and use it in GitHub Desktop.
Save rf-/1147702 to your computer and use it in GitHub Desktop.
module Instantizable
def instantize(name)
klass = self
define_method(name) do |*args, &block|
klass.send(name, self, *args, &block)
end
end
end
# Test the module with a normal method, a method with a hash arg, and a method with a block.
module ModuleOne
extend Instantizable
def self.caps_reverse(obj)
obj.reverse.upcase
end
instantize :caps_reverse
end
raise if ModuleOne.caps_reverse("string") !=
"string".extend(ModuleOne).caps_reverse
module ModuleTwo
extend Instantizable
def self.yield_and_upcase(obj)
yield(obj).upcase
end
instantize :yield_and_upcase
end
raise if ModuleTwo.yield_and_upcase("string") { |str| str + 'more_stuff' } !=
"string".extend(ModuleTwo).yield_and_upcase { |str| str + 'more_stuff' }
module ModuleThree
extend Instantizable
def self.extract_a(obj)
obj[:a]
end
instantize :extract_a
end
raise if ModuleThree.extract_a(:a => 1, :b => 2) !=
({:a => 1, :b => 2}).extend(ModuleThree).extract_a
@vivien
Copy link

vivien commented Aug 15, 2011

Why not using this?
So you don't need to open the Module class (as you've just shown me on irc btw ;)).

module MyModule
  def self.caps_reverse str
    str.upcase.reverse
  end

  def caps_reverse
    MyModule.caps_reverse self
  end
end

MyModule.caps_reverse "blah" # => "HALB"
"blah".extend(MyModule).caps_reverse # => "HALB"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment