Created
March 24, 2017 16:26
-
-
Save purinkle/c28d40d614f9887d894ae0ae7a197796 to your computer and use it in GitHub Desktop.
An example of an extensible responder factory
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
class ProductCreationResponder | |
@@responders = [] | |
def self.build(product) | |
responders.detect do |responder| | |
responder.applicable_to?(product) | |
end.new(product) | |
end | |
def self.register(responder) | |
@@responders << responder | |
end | |
class FailureResponder | |
ProductCreationResponder.register self | |
def self.applicable_to?(product) | |
product.errors.any? | |
end | |
def initialize(product) | |
@product = product | |
end | |
def call(responses) | |
responses.fetch(response).call(product) | |
end | |
private | |
attr_reader :product | |
def response | |
:on_failure | |
end | |
end | |
class SuccessResponder | |
ProductCreationResponder.register self | |
def self.applicable_to?(product) | |
product.errors.empty? | |
end | |
def initialize(product) | |
@product = product | |
end | |
def call(responses) | |
responses.fetch(response).call(product) | |
end | |
private | |
attr_reader :product | |
def response | |
:on_success | |
end | |
end | |
end | |
ProductCreationResponder.build(product).call( | |
on_failure: on_failure, | |
on_success: on_success, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment