Class: MrDarcy::Context

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/mr_darcy/context.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(role_players = {}) ⇒ Context

Create an instance of the context. You must pass in role-players for all roles defined in this context using a single hash argument of role names (as symbols) to objects.

eg:

BankTransfer.new money_source: account1, money_destination: account2

48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/mr_darcy/context.rb', line 48

def initialize role_players={}
  @driver   = role_players.delete(:driver) || MrDarcy.driver
  @deferred = Deferred.new(driver: driver)
  deferred.resolve nil

  roles = self.class.roles
  roles.each do |role_name, role|
    player = role_players[role_name]
    Kernel::raise ArgumentError, "No role player for #{role_name} supplied" unless player

    role.pollute(player)

    self.singleton_class.send :define_method, role_name do
      player
    end
  end
end

Class Method Details

.action(action_name, &block) ⇒ Object

Defines an action that can be performed in this context.

  • action_name: essentially the name of the method defined in this class.

Takes a block with which to define the action.


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

def action action_name, &block
  define_method action_name do |*args|
    self.then do |value|
      self.instance_exec(*args, &block)
    end
    self
  end
end

.role(role_name, options = {}, &block) ⇒ Object

Defines a role to be mixed into the roll-player when this context is initialized.

See MrDarcy::Role#initialize for argument definitions.


16
17
18
# File 'lib/mr_darcy/context.rb', line 16

def role role_name, options={}, &block
  self.roles[role_name] = Role.new(role_name, options, &block)
end

.rolesObject

A list of available roles in this context.


36
37
38
# File 'lib/mr_darcy/context.rb', line 36

def roles
  @roles ||= {}
end

Instance Method Details

#fail(&block) ⇒ Object

See MrDarcy::Promise::Base#fail


75
76
77
78
79
80
# File 'lib/mr_darcy/context.rb', line 75

def fail &block
  deferred.fail do |value|
    self.instance_exec(value, &block)
  end
  self
end

#finalObject

See MrDarcy::Promise::Base#final


83
84
85
86
# File 'lib/mr_darcy/context.rb', line 83

def final
  deferred.final
  self
end

#then(&block) ⇒ Object

See MrDarcy::Promise::Base#then


67
68
69
70
71
72
# File 'lib/mr_darcy/context.rb', line 67

def then &block
  deferred.then do |value|
    self.instance_exec(value, &block)
  end
  self
end