Module: Expando::Expander

Defined in:
lib/expando/expander.rb

Constant Summary collapse

TOKEN_REGEX =
/(?<!\\)\((.*?)\)/

Class Method Summary collapse

Class Method Details

.expand!(lines) ⇒ Array

Generate a new ‘Expander`.

Parameters:

  • lines (Array<String>)

    The text to scan and expand.

Returns:

  • (Array)

    The expanded text.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/expando/expander.rb', line 24

def expand!( lines )
  expanded_lines = []

  lines.each do |line|
    tokens = line.scan TOKEN_REGEX

    # Don't perform expansion if no tokens are present.
    if tokens.empty?
      expanded_lines << line
      next
    end

    expanded_tokens = []
    tokens.each_with_index do |token, index|
      expanded_tokens[index] = token[0].split( '|' )
    end

    # Produce Cartesian product of all tokenized values.
    token_product = expanded_tokens[ 0 ].product( *expanded_tokens[ 1..-1 ] )

    # Generate new expanded lines.
    token_product.each do |replacement_values|
      expanded_line = line

      replacement_values.each do |value|
        expanded_line = expanded_line.sub( TOKEN_REGEX, value )
      end

      # TODO: Replace multiple spaces with a single space
      expanded_lines << expanded_line.strip
    end
  end

  expanded_lines
end