Created
December 1, 2014 19:55
-
-
Save brianknapp/046a9787ac85898ec19b to your computer and use it in GitHub Desktop.
Messages
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
## This is an experiment in stronger message handling protocols in Ruby. | |
module BasicProtocol | |
def method_missing(method, *args, &block) | |
if respond_to? :handle_missing_method | |
return handle_missing_method(method, *args, &block) | |
else | |
return { error: "no method found!" } | |
end | |
end | |
def respond_to_missing?(method_name, include_private = false) | |
method_name.to_s != "handle_missing_method" || super | |
end | |
end | |
module DerpProtocol | |
include BasicProtocol | |
def wat message | |
# silly precondition | |
if message[:foo].nil? | |
return { error: 'precondition fail whale!' } | |
end | |
result = super | |
# silly postcondition | |
if result[:success] != true | |
return { error: 'postcondition fail whale!' } | |
end | |
# result | |
return result | |
end | |
end | |
class Derp | |
prepend DerpProtocol | |
def wat message | |
{ success: true } | |
end | |
end | |
class CustomErrorDerp | |
prepend DerpProtocol | |
def handle_missing_method method, *args | |
return { error: "custom no method found!" } | |
end | |
end | |
# run program | |
foo = Derp.new | |
puts foo.wat foo: 'wat' | |
puts foo.wat something: 'wat' | |
puts foo.abc_method | |
foo2 = CustomErrorDerp.new | |
puts foo2.abc_method | |
# expected output: | |
# | |
# {:success=>true} | |
# {:error=>"precondition fail whale!"} | |
# {:error=>"no method found!"} | |
# {:error=>"custom no method found!"} | |
# |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment