Class: JSound::Midi::Devices::Transformer

Inherits:
JSound::Midi::Device show all
Defined in:
lib/jsound/midi/devices/transformer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from JSound::Midi::Device

#<=, #>>, #close, #open, #open?, #output, #output=, #to_s, #type

Methods included from TypeFromClassName

included

Constructor Details

#initialize(mappings = nil, &transform) ⇒ Transformer

Returns a new instance of Transformer.

Parameters:

  • mappings (Hash) (defaults to: nil)

    a Hash of mappings (see #mappings). When not nil, #clone will be automatically set to true. Set #clone to false by including the entry => false

  • &transform


22
23
24
25
26
27
# File 'lib/jsound/midi/devices/transformer.rb', line 22

def initialize(mappings=nil, &transform)
  @clone = !!mappings.fetch(:clone, true) if mappings
  mappings.delete :clone if mappings
  @mappings = mappings
  @transform = transform
end

Instance Attribute Details

#cloneObject

If true, messages will be automatically cloned when received by this device. Messages are mutable, so in many cases it’s important to clone a message before changing it.



12
13
14
# File 'lib/jsound/midi/devices/transformer.rb', line 12

def clone
  @clone
end

#mappingsObject

A Hash of mappings, with entries in the format {:message_attribute => lambda{|attribute| … } }



8
9
10
# File 'lib/jsound/midi/devices/transformer.rb', line 8

def mappings
  @mappings
end

#transformObject

The transformation block: a lambda that takes a message and returns either a transformed message or an Enumerable list of messages



16
17
18
# File 'lib/jsound/midi/devices/transformer.rb', line 16

def transform
  @transform
end

Instance Method Details

#message(message) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/jsound/midi/devices/transformer.rb', line 29

def message(message)
  message = message.clone if @clone

  for attr, mapping in @mappings
    setter = "#{attr}="
    message.send setter, mapping[message.send attr] if message.respond_to? attr and message.respond_to? setter
  end if @mappings

  if @output
    if @transform
      message = @transform[message]
      if message.is_a? Enumerable
        message.each{|m| @output.message(m) }
      else
        super(message) if message
      end

    elsif @clone or !@mappings.empty?
      super(message)
    end
  end
end