Module: AutoStacker24::Preprocessor

Defined in:
lib/autostacker24/template_preprocessor.rb

Class Method Summary collapse

Class Method Details

.preprocess(template) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/autostacker24/template_preprocessor.rb', line 8

def self.preprocess(template)
  if template =~ /^\s*\/{2}\s*/i
    template = template.gsub(/(\s*\/\/.*$)|(".*")/) {|m| m[0] == '"' ? m : ''} # replace comments
    template = preprocess_json(JSON(template)).to_json
  end
  template
end

.preprocess_json(json) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/autostacker24/template_preprocessor.rb', line 16

def self.preprocess_json(json)
  if json.is_a?(Hash)
    json.inject({}){|m, (k, v)| m.merge(k => preprocess_json(v))}
  elsif json.is_a?(Array)
    json.map{|v| preprocess_json(v)}
  elsif json.is_a?(String)
    preprocess_string(json)
  else
    json
  end
end

.preprocess_string(s) ⇒ Object



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
# File 'lib/autostacker24/template_preprocessor.rb', line 28

def self.preprocess_string(s)
  parts = tokenize(s).map do |token|
    case token
      when '@@' then '@'
      when /^@/ then {'Ref' => token[1..-1]}
      else token
    end
  end

  # merge neighboured strings
  parts = parts.reduce([])do |m, p|
    if m.last.is_a?(String) && p.is_a?(String)
      m[-1] += p
    else
      m << p
    end
    m
  end

  if parts.length == 1
    parts.first
  else # we need a join construct
    {'Fn::Join' => ['', parts]}
  end
end

.tokenize(s) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/autostacker24/template_preprocessor.rb', line 54

def self.tokenize(s)
  pattern = /@@|@([\w:]+)/
  tokens = []
  loop do
    m = pattern.match(s)
    if m
      tokens << m.pre_match unless m.pre_match.empty?
      tokens << m.to_s
      s = m.post_match
    else
      tokens << s unless s.empty? && !tokens.empty?
      break
    end
  end
  tokens
end