Skip to content

Instantly share code, notes, and snippets.

@aruprakshit
Forked from wycats/dispatcher.rb
Last active Aug 29, 2015
Embed
What would you like to do?
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
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