Class: Mediate::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/mediate/request.rb

Overview

The base class of a request that can be dispatched to the mediator, which returns a response from its handler.

Class Method Summary collapse

Class Method Details

.create_implicit_handlerMediate::RequestHandler

If an implicit handler is defined for this Request using the #handle_with method, this will return an instance of it. Use this for testing the handler.

Examples:

Create an instance and call #handle on it to test it

handler = MyRequest.create_implicit_handler
result = handler.handle(MyRequest.new)

Returns:

Raises:

  • (RuntimeError)

    if no implicit handler is defined



46
47
48
49
50
# File 'lib/mediate/request.rb', line 46

def self.create_implicit_handler
  raise "Implicit handler is not defined." unless implicit_handler_defined?

  const_get(IMPLICIT_HANDLER_CLASS_NAME).new
end

.handle_with(lmbda, mediator = Mediate.mediator) ⇒ Object

Registers a handler for this Request type using the given lambda as the handle method.

Examples:

When a request of this type is dispatched, the handle_with lambda will run

class MyRequest < Mediate::Request
  handle_with lambda do |request|
    ## do something with request...
  end
end

Parameters:

  • lmbda (Lambda)

    the block that will handle the request

  • mediator (Mediate::Mediator) (defaults to: Mediate.mediator)

    the instance to register the handler on

Raises:

  • (ArgumentError)


26
27
28
29
30
31
32
33
# File 'lib/mediate/request.rb', line 26

def self.handle_with(lmbda, mediator = Mediate.mediator)
  raise ArgumentError, "expected lambda to be passed to #handle_with." if lmbda.nil?

  handler_class = define_handler(lmbda)
  undefine_implicit_handler # remove any previous definition (this will do nothing if it doesn't exist)
  const_set(IMPLICIT_HANDLER_CLASS_NAME, handler_class)
  mediator.register_request_handler(handler_class, self)
end

.undefine_implicit_handlerObject



52
53
54
55
56
# File 'lib/mediate/request.rb', line 52

def self.undefine_implicit_handler
  return unless implicit_handler_defined?

  remove_const(IMPLICIT_HANDLER_CLASS_NAME)
end