Skip to content

Instantly share code, notes, and snippets.

@okitan
Created January 18, 2013 12:44
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 okitan/4564339 to your computer and use it in GitHub Desktop.
Save okitan/4564339 to your computer and use it in GitHub Desktop.
なんとなく
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