File: composite.rb

package info (click to toggle)
ruby-stamp 0.6.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 204 kB
  • sloc: ruby: 371; makefile: 2
file content (42 lines) | stat: -rw-r--r-- 902 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
module Stamp
  module Emitters
    class Composite
      include Enumerable

      attr_reader :emitters

      def initialize(emitters=[])
        @emitters = emitters
      end

      def format(target)
        # NOTE using #each to build string because benchmarking shows
        # that it's ~20% faster than .map.join('')
        result = ''
        emitters.each { |e| result << e.format(target).to_s }
        result
      end

      def <<(emitter)    
        Array(emitter).each { |e| emitters << e }
      end

      def each(&block)
        emitters.each(&block)
      end

      def -(others)
        emitters - Array(others)
      end

      # Replace each element as we iterate with the result of the given block.
      def replace_each!
        emitters.each_with_index do |emitter, index|
          emitters[index] = yield(emitter)
        end

        self
      end
    end
  end
end