Class: Vissen::Input::MessageFactory
- Inherits:
-
Object
- Object
- Vissen::Input::MessageFactory
- 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
-
#add_matcher(matcher) ⇒ self
Inserts another matcher to the list of known input data matchers.
-
#build(obj, timestamp) ⇒ Message
Creates a new Message object by matching the data against the stored message classes.
-
#freeze ⇒ self
Prevents any more matchers from being added.
-
#initialize(matchers = nil) ⇒ MessageFactory
constructor
A new instance of MessageFactory.
Constructor Details
#initialize(matchers = nil) ⇒ MessageFactory
Returns a new instance of MessageFactory.
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.
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.
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, ) data = obj.to_a klass = if obj.is_a?(Message) && obj.valid? return obj if obj. == obj.class else matcher = lookup data matcher ? matcher.klass : Message::Unknown end klass.new data, end |
#freeze ⇒ self
Prevents any more matchers from being added.
38 39 40 41 |
# File 'lib/vissen/input/message_factory.rb', line 38 def freeze @matchers.freeze super end |