Created
February 9, 2012 13:18
-
-
Save iande/1779895 to your computer and use it in GitHub Desktop.
Wrapping class singleton (eigen) methods with a module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: MyFinalApproach defines a block that takes a block, | |
# which only works with Ruby >= 1.9. To work with 1.8, you'll need | |
# to take that bit out. | |
# Also, I think 'eigen' contains more phonetic badassery than | |
# 'singleton', which is the real reason I prefer it. | |
require 'forwardable' | |
class SomeClass | |
def self.my_eigen_method; 42; end | |
def self.my_other_eigen_method; :truck; end | |
end | |
module MyModule | |
class << self | |
extend Forwardable | |
def_delegators :real_receiver, :my_eigen_method, :my_other_eigen_method | |
def real_receiver; SomeClass; end | |
end | |
end | |
module MyOtherApproach | |
extend Forwardable | |
extend MyOtherApproach | |
def_delegators :real_receiver, :my_eigen_method, :my_other_eigen_method | |
def real_receiver; SomeClass; end | |
end | |
module MyFinalApproach | |
extend MyFinalApproach | |
SomeClass.singleton_methods.each do |meth| | |
define_method(meth) do |*args, &blk| | |
SomeClass.__send__ meth, *args, &blk | |
end | |
end | |
end | |
puts "And the winner is: #{MyModule.my_eigen_method}" | |
puts "And the other winner is: #{MyOtherApproach.my_eigen_method}" | |
puts "And the final winner is: #{MyFinalApproach.my_eigen_method}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment