Created
January 18, 2013 12:44
-
-
Save okitan/4564339 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
module Dispatchable | |
def self.included(base) | |
base.module_eval { | |
def self.method_added(name) | |
suffix = self.name.split("::").last.downcase | |
return if name.to_s.end_with?(suffix) | |
module_eval %{ | |
alias #{name}_#{suffix} #{name} | |
undef #{name} | |
} | |
end | |
} | |
end | |
def define_dispatch_rule(&block) | |
__send__(:define_method, :dispatch_rule) do |target| | |
block.call(target) | |
end | |
end | |
def dispatch_methods(*methods) | |
opts = ( methods.last.is_a?(Hash) ? methods.pop : { :default => :orig }) | |
methods.flatten.each do |method| | |
default_method = [ method, opts[:default] ].join("_") | |
if instance_methods.include?(method.to_sym) && !instance_methods.include?(default_method.to_sym) | |
module_eval %{ | |
alias #{default_method} #{method} | |
} | |
end | |
__send__(:define_method, method) do |*args| | |
method_to_dispatch = [ method, dispatch_rule(self) ].join("_") | |
method_to_dispatch = default_method unless respond_to?(method_to_dispatch) | |
__send__(method_to_dispatch, *args) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment