Class: ChainReactor::Reactor

Inherits:
Object
  • Object
show all
Defined in:
lib/chain-reactor/reactor.rb

Overview

Contains the map of reactions and allowed client addresses.

This is used to determine which clients are allowed to connect, and to dispatch reactions.

Instance Method Summary collapse

Constructor Details

#initialize(logger) ⇒ Reactor

Pass a logger object and define an empty address map.



11
12
13
14
# File 'lib/chain-reactor/reactor.rb', line 11

def initialize(logger)
  @address_map = {}
  @log = logger
end

Instance Method Details

#add(addresses, options, block) ⇒ Object

Add a react_to block from the chain file.

Creates a Reaction object and calls add_address().



19
20
21
22
# File 'lib/chain-reactor/reactor.rb', line 19

def add(addresses,options,block)
  reaction = Reaction.new(options,block,@log)
  addresses.each { |addr| add_address(addr,reaction) }
end

#add_address(address, reaction) ⇒ Object

Add an address with a reaction.



25
26
27
28
29
30
31
32
33
# File 'lib/chain-reactor/reactor.rb', line 25

def add_address(address,reaction)
  @log.debug { "Linking reaction to address #{address}" }

  if @address_map.has_key? address
    @address_map[address] << reaction
  else
    @address_map[address] = [reaction]
  end
end

#address_allowed?(address) ⇒ Boolean

Check whether the IP address is allowed.

An IP address is allowed if the chain file specifies a “react_to” block with that address.

Returns:

  • (Boolean)


64
65
66
# File 'lib/chain-reactor/reactor.rb', line 64

def address_allowed?(address)
  @address_map.has_key? address
end

#react(address, data_string) ⇒ Object

React to a client by running the associated reactions.

Raises an error if the address is not allowed - use address_allowed? first.



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/chain-reactor/reactor.rb', line 39

def react(address,data_string)
  address_allowed?(address) or raise 'Address is not allowed'
  @address_map[address].each do |reaction|
    @log.info { "Executing reaction for address #{address}" }
    begin
      reaction.execute(data_string)
    rescue Parsers::ParseError => e
      @log.error { "Parser error: #{e.message}" }
    rescue Parsers::RequiredKeyError => e
      @log.error { "Client data invalid: #{e.message}" }
    rescue ReactionError => e
      @log.error { 'Exception raised in reaction: '+e.message }
    end
  end
end

#reactions_for(address) ⇒ Object

Get an array of reactions for a given address



56
57
58
# File 'lib/chain-reactor/reactor.rb', line 56

def reactions_for(address)
  @address_map[address] if address_allowed?(address)
end