Created
August 25, 2009 07:06
-
-
Save wycats/174521 to your computer and use it in GitHub Desktop.
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
class Object | |
def send_through(object, *args) | |
object.dispatcher_for(self).call(self, *args) | |
end | |
end | |
module Dispatcher | |
class DispatcherNotFound < StandardError; end | |
def self.extended(klass) | |
klass.class_eval { @dispatchers = {} } | |
end | |
def for(kind, &block) | |
@dispatchers[kind] = block | |
end | |
def dispatcher_for(object) | |
return @dispatchers[object.class] ||= begin | |
klass = object.class | |
until klass == Object | |
if @dispatchers.key?(klass) | |
return @dispatchers[object.class] = @dispatchers[klass] | |
end | |
klass = klass.superclass | |
end | |
raise DispatcherNotFound, "No #{self} dispatcher for #{object.class}" | |
end | |
end | |
end |
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
module Camelize | |
extend Dispatcher | |
end | |
Camelize.for(String) do |string| | |
string.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } | |
end | |
Camelize.for(Object) do |object| | |
"" | |
end | |
p "hello_hello".send_through(Camelize) | |
p nil.send_through(Camelize) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment