Skip to content

Instantly share code, notes, and snippets.

@mhink
Last active October 22, 2015 23:26
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 mhink/16783d03dfd7576a58f8 to your computer and use it in GitHub Desktop.
Save mhink/16783d03dfd7576a58f8 to your computer and use it in GitHub Desktop.
Dynamic Dispatch: Compare/Contrast
class DynamicMethodDispatchExample
def do_something(what_to_do)
begin
self.send("provide_#{what_to_do}_string")
rescue NoMethodError => ex
raise ArgumentError
end
end
def provide_foo_string
FOO
end
def provide_bar_string
BAR
end
def provide_baz_string
BAZ
end
end
class CaseStatementExample
def do_something(what_to_do)
case what_to_do.to_s
when "foo"
provide_foo_string
when "bar"
provide_bar_string
when "baz"
provide_baz_string
else
raise ArgumentError
end
end
def provide_foo_string
FOO
end
def provide_bar_string
BAR
end
def provide_baz_string
BAZ
end
end
class ClassConstantLookupExample
def do_something(what_to_do)
provider_class = "#{self.class.name}::#{what_to_do.to_s.classify}Provider".constantize
raise ArgumentError unless (provider_class < Provider)
provider_class.new.provide_string
end
class Provider
def provide_string
raise "Unimplemented method."
end
end
class FooProvider < Provider
def provide_string
FOO
end
end
class BarProvider < Provider
def provide_string
BAR
end
end
class BazProvider < Provider
def provide_string
BAZ
end
end
end
class ModuleConstantLookupExample
def do_something(what_to_do)
provider_module = "#{self.class.name}::#{what_to_do.to_s.classify}Provider".constantize
do_something_with_provider(provider_module)
end
def do_something_with_provider(provider)
raise ArgumentError unless provider.respond_to? :provide_string
provider.provide_string
end
module FooProvider
def self.provide_string
FOO
end
end
module BarProvider
def self.provide_string
BAR
end
end
module BazProvider
def self.provide_string
BAZ
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment