Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
DSLs in ruby
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