Skip to content

Instantly share code, notes, and snippets.

@clupprich
Last active November 5, 2015 06:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clupprich/bfb67f10d813d726939a to your computer and use it in GitHub Desktop.
Save clupprich/bfb67f10d813d726939a to your computer and use it in GitHub Desktop.
Interactor
# Finally, all comes together in an interactor
class CreateMailgunDomain
include Interactor
include MailgunApi
pattr_initialize :domain
def call
response = post('/domains', name: domain, smtp_password: random_password)
if response.code == 200
response
else
fail!(response)
end
end
private
def random_password
SecureRandom.hex
end
end
# Defines the failure object, which (optionally) takes an object and a message.
class Failure < StandardError
attr_reader :object
def initialize(object = nil, message = nil)
super(message)
@object = object
end
end
# Offers the #fail! method and implicitely returns a successful `Result` with the return value.
module Interactor
def self.included(base)
base.extend(ClassMethods)
end
def fail!(object = nil)
self.class.fail!(object)
end
module ClassMethods
def call(*args)
object = new(*args).call
Result.new(true, object)
rescue Failure => failure
Result.new(false, failure.object)
end
def fail!(object = nil)
fail Failure, object
end
end
end
# Reponds to success? and failure?. Also uses `SimpleDelegator` to make accessing the underyling object a bit nicer.
class Result < SimpleDelegator
def initialize(success, object = nil)
@success = success
super(object)
end
def success?
@success
end
def failure?
!@success
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment