Class: Vissen::Input::MessageFactory

Inherits:
Object
  • Object
show all
Defined in:
lib/vissen/input/message_factory.rb

Overview

The facatory takes raw input messages and builds matching objects around them. It stores a list of input matchers that it knows about.

If an array of matchers is passed to the constructor the MessageFactory will freeze itself to create an immutable factory.

TODO: Sort the matchers on input frequency for performance?

== Usage The following example sets up a factory to build ControlChange messages.

matcher = Message::ControlChange.matcher factory = MessageFactory.new [matcher]

factory.build [0xC0, 3, 42], 0.0 # => Message::ControlChange factory.build [0xB0, 0, 0], 0.0 # => Message::Unknown

Instance Method Summary collapse

Constructor Details

#initialize(matchers = nil) ⇒ MessageFactory

Returns a new instance of MessageFactory.

Parameters:

  • matchers (nil, Array<Matcher>) (defaults to: nil)

    the matchers to use when building messages. If provided the factory will be frozen after creation.



25
26
27
28
29
30
31
32
33
# File 'lib/vissen/input/message_factory.rb', line 25

def initialize(matchers = nil)
  @lookup_table = Array.new(16) { [] }
  @matchers     = []

  return unless matchers

  matchers.each { |m| add_matcher m }
  freeze
end

Instance Method Details

#add_matcher(matcher) ⇒ self

Inserts another matcher to the list of known input data matchers.

Parameters:

  • matcher (Matcher)

    the matcher to add.

Returns:

  • (self)

Raises:

  • (TypeError)


47
48
49
50
51
# File 'lib/vissen/input/message_factory.rb', line 47

def add_matcher(matcher)
  raise TypeError unless matcher.is_a? Matcher
  @matchers << matcher
  self
end

#build(obj, timestamp) ⇒ Message

Creates a new Message object by matching the data against the stored message classes.

Parameters:

  • obj (#to_a)

    the data object to build the new message arround.

  • timestamp (Float)

    the time that the message was first received.

Returns:



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/vissen/input/message_factory.rb', line 59

def build(obj, timestamp)
  data  = obj.to_a
  klass =
    if obj.is_a?(Message) && obj.valid?
      return obj if obj.timestamp == timestamp
      obj.class
    else
      matcher = lookup data
      matcher ? matcher.klass : Message::Unknown
    end

  klass.new data, timestamp
end

#freezeself

Prevents any more matchers from being added.

Returns:

  • (self)


38
39
40
41
# File 'lib/vissen/input/message_factory.rb', line 38

def freeze
  @matchers.freeze
  super
end