Last active
February 15, 2019 02:44
-
-
Save RichardJordan/39f32d18495276cbee1bf36b7eb28db2 to your computer and use it in GitHub Desktop.
Use Cases pattern spike - part 2
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
# 2. In order to enable that previous example of a handler to | |
# deal with all of the transactions use cases, for a transactions | |
# controller, we'd need a base class that looks something like this: | |
module UseCases | |
class Base | |
class << self | |
def commands | |
@commands ||= {} | |
end | |
def permitted_use_cases | |
commands.keys | |
end | |
def register_command(command_name, on:) | |
commands[on] = command_name | |
end | |
end | |
attr_reader :command_args, :listener | |
def initialize(listener) | |
@listener = listener | |
end | |
def execute(use_case, context: {}, on_success:, on_failure:) | |
raise CommandNotPermitted unless permitted_use_cases.include?(use_case) | |
build_command_args(context, on_success, on_failure) | |
call_command_for use_case | |
end | |
def permitted_use_cases | |
self.class.permitted_use_cases | |
end | |
private | |
def build_command_args(context, on_success, on_failure) | |
@command_args ||= { | |
listener: listener, | |
on_success: on_success, | |
on_failure: on_failure | |
}.merge!(context) | |
end | |
def call_command_for(use_case) | |
case command_name = command_names(use_case) | |
when String | |
command_name.constantize.new(command_args).call | |
when Symbol | |
send command_name | |
end | |
end | |
def commands | |
self.class.commands | |
end | |
def failure(failure_return_value=nil) | |
listener.send command_args[:on_failure], failure_return_value | |
end | |
def success(success_return_value=nil) | |
listener.send command_args[:on_success], success_return_value | |
end | |
end | |
end | |
# part 3: https://gist.github.com/RichardJordan/cad1513c121796259bcfe097bf269b22 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment