Class: Munger::Munge

Inherits:
Object
  • Object
show all
Defined in:
lib/munger/munge.rb

Constant Summary collapse

OPTIONS =
[:mode, :pattern, :tag, :content, :content_path, :input,
:input_path, :output, :output_path, :path, :verbose]

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Munge

Returns a new instance of Munge.



15
16
17
18
19
20
21
22
23
24
25
# File 'lib/munger/munge.rb', line 15

def initialize(options)
  self.mode = options[:mode] || :append
  self.pattern = Regexp.compile(options[:pattern]) unless mode == :append
  self.tag = options[:tag] || ''
  self.verbose = options[:verbose]

  if verbose
    settings = OPTIONS.map {|attr| "#{attr} = #{eval "#{attr}.inspect"}" }
    puts settings.join(', ')
  end
end

Instance Method Details

#run(input, content) ⇒ Object



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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/munger/munge.rb', line 27

def run(input, content)
  startTag = tag + " (munge start)"
  endTag = tag + " (munge end)"
  content = [startTag, content.rstrip, endTag].join("\n")

  result = []
  skipping = nil
  needMatch = [:before, :replace, :after, :replace_or_append].include? mode
  input.split("\n").each do |l|
    if skipping
      if l == endTag
        puts "Done skipping: #{l}" if verbose
        skipping = nil
        if [:replace, :replace_or_append].include?(mode)
          puts "Inserting content" if verbose
          result << content
        end
      else
        puts "Skipping: #{l}" if verbose
      end
    elsif l == startTag
      puts "Start skipping: #{l}" if verbose
      skipping = true
      needMatch = nil
    else
      matched = needMatch && pattern.match(l)
      if mode == :before && matched
        puts "Matched (before): inserting before #{l}" if verbose
        result << content
        needMatch = nil
      end
      if [:replace, :replace_or_append].include?(mode) && matched
        puts "Matched (#{mode}): replacing #{l}" if verbose
        result << content
        needMatch = nil
      else
        puts "Using existing line #{l}" if verbose
        result << l
      end
      if mode == :after && matched
        puts "Matched (after): inserting after #{l}" if verbose
        result << content
        needMatch = nil
      end
    end
  end

  if mode == :append or (mode == :replace_or_append && needMatch)
    puts "Appending..." if verbose
    result << content
  end

  result << "" # make sure we end with a newline
  result.join("\n")
end