-
-
Save clupprich/bfb67f10d813d726939a to your computer and use it in GitHub Desktop.
Interactor
This file contains 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
# 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 |
This file contains 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
# 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 |
This file contains 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
# 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 |
This file contains 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
# 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