Created
January 17, 2016 04:29
-
-
Save octosteve/ef40f49323614674546a to your computer and use it in GitHub Desktop.
This file contains 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
require 'pry' | |
module DefineMulti | |
def method_missing(original_caller, *args) | |
the_method = "_#{args.length}_#{original_caller}".to_sym | |
unless self.methods.include?(the_method) | |
raise NoMethodError, "Undefined method '#{original_caller}' with arity #{args.size}" | |
end | |
public_send(the_method, *args) | |
end | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def method_added(the_method) | |
@overloaded_methods ||= Hash.new{|k,v| k[v] = []} | |
return if @overloaded_methods.values.flatten.include?(the_method) | |
method_obj = instance_method(the_method) | |
arity = method_obj.arity | |
new_method_name = "_#{arity}_#{the_method}".to_sym | |
@overloaded_methods[the_method] << new_method_name | |
alias_method new_method_name, the_method | |
undef_method the_method | |
end | |
def define_multi(&block) | |
class_eval(&block) | |
end | |
end | |
end | |
class MultiClass | |
include DefineMulti | |
define_multi do | |
def multiple_heads(arg) | |
puts "One Arg" | |
end | |
def multiple_heads(arg1, arg2) | |
puts "Two Args" | |
end | |
end | |
end | |
MultiClass.new.multiple_heads("beef") | |
MultiClass.new.multiple_heads("beef", "ham") | |
MultiClass.new.multiple_heads("beef", "ham", "chicken") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment