Module: Junkfood::Ceb::Bus::ClassMethods

Defined in:
lib/junkfood/ceb/bus.rb

Overview

Methods to add to the actual classes that include Junkfood::Ceb::Bus.

Instance Method Summary collapse

Instance Method Details

#acts_as_bus(bus_type, executor = nil) ⇒ Object

Creates:

  • a class attribute for the bus executor.

  • an instance method to put a message onto the bus.

Parameters:

  • bus_type (Symbol)

    the name of the bus.

  • executor (#call) (defaults to: nil)

    a handler for the bus’ messages.



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/junkfood/ceb/bus.rb', line 100

def acts_as_bus(bus_type, executor=nil)
  class_eval do
    # We create the class attributes (accessors) for this executor
    # so individual instances or subclasses can override this.
    # And it sets it to the given executor or an empty executor
    executor_name = "#{bus_type}_executor"
    class_attribute executor_name
    send "#{executor_name}=", (executor || Proc.new {})

    # Now we define a the bus method in the form of `send_<bus_type>`.
    # This is the main method that objects call to look up the
    # commands/events, instantiate them, and execute on them.
    # This method will return the created command/event along with
    # the executor's results.
    method_name = "send_#{bus_type}"
    define_method(method_name, lambda { |name, *args|
      klass = "#{name}_#{bus_type}".to_s.classify.constantize
      message = klass.new *args
      results = message.valid? ? send(executor_name).call(message) : nil
      return message, results
    })
  end
end

#acts_as_command_bus(executor = ::Junkfood::Ceb::Executors::CommandExecutor.new) ⇒ Object

Creates:

  • command_executor class attributes.

  • send_command instance method to put commands onto the bus.

Parameters:

  • executor (#call) (defaults to: ::Junkfood::Ceb::Executors::CommandExecutor.new)

    an actual executor to use instead of the default ::Junkfood::Ceb::Executors::CommandExecutor.



132
133
134
135
# File 'lib/junkfood/ceb/bus.rb', line 132

def acts_as_command_bus(
    executor=::Junkfood::Ceb::Executors::CommandExecutor.new)
  acts_as_bus :command, executor
end

#acts_as_event_bus(executor = ::Junkfood::Ceb::Executors::EventExecutor.new) ⇒ Object

Creates:

  • event_executor class attributes.

  • send_event instance method to put events onto the bus.

Parameters:

  • executor (#call) (defaults to: ::Junkfood::Ceb::Executors::EventExecutor.new)

    an actual executor to use instead of the default ::Junkfood::Ceb::Executors::EventExecutor.



145
146
147
148
# File 'lib/junkfood/ceb/bus.rb', line 145

def acts_as_event_bus(
    executor=::Junkfood::Ceb::Executors::EventExecutor.new)
  acts_as_bus :event, executor
end