Created
October 8, 2014 21:05
-
-
Save saturnflyer/37d892231b1e89516257 to your computer and use it in GitHub Desktop.
DSLs in ruby
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 Something | |
def self.protector(name, &block) | |
begin | |
call_mod = self.const_get(:ExternalSystemCalls, false) | |
rescue NameError | |
call_mod = Module.new | |
const_set(:ExternalSystemCalls, call_mod) | |
include call_mod | |
end | |
begin | |
protected_mod = self.const_get(:ProtectedCalls, false) | |
rescue NameError | |
protected_mod = Module.new | |
const_set(:ProtectedCalls, protected_mod) | |
include protected_mod | |
end | |
# Define the method that acutally does the call | |
call_mod.send(:define_method, name, &block) | |
# Define the method that wraps the call | |
protected_mod.class_eval %{ | |
def #{name}(*args, &block) | |
super | |
rescue ExternalApiError => exception | |
# do something with the exception | |
return some value or raise your own error | |
ensure | |
# perform some cleanup | |
end | |
} | |
end | |
protector :signup do | |
endpoint.call(:signup, true, "and other stuff", :whatever) | |
end | |
protector :disable do | |
endpoint.call(:disable, false, "no idea what you'd do here", :nope) | |
end | |
# do this if you want to debug | |
def disable(*) | |
binding.pry | |
super | |
end | |
# then delete this method after debugging. | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment