Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active October 19, 2016 20:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/dd222aaa70ce543bf648a25fa5823b71 to your computer and use it in GitHub Desktop.
Save krisleech/dd222aaa70ce543bf648a25fa5823b71 to your computer and use it in GitHub Desktop.
Commands, Events, Dependency Injection
class MyCommand
  include Wisper::Publisher

  def initialize(dependencies = {})
    @token_generator = depdendencies.fetch(:token_generator) do
       require 'generate_token'
       GenerateToken.new
     end
  end

  def call(params, &block)
    yield if block_given?
    
    if all_good?
      broadcast(:successful, { id: id })
    else
      broadcast(:failure, { errors: errors })
    end
  end
  
  private
  
  def on(event, handler)
    # ...
  end
end

# app initalization process
System = {}
System[:my_command] = MyCommand.new

# handle request from UI (e.g. in a controller)
System[:my_command].call(params) do
  on(:success) { }
  on(failure) { }
end

The command must be stateless so one instance can be invoked many times over the lifetime of the application.

TODO: The on subscribers need to be temporary since we are using one instance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment