Top Level Namespace

Defined Under Namespace

Modules: Subtxt

Instance Method Summary collapse

Instance Method Details

#display_results(routine = {}) ⇒ Object



92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/subtxt.rb', line 92

def display_results routine={}
  raise "NoRecordsFound" unless routine['log'].count
  output = "Files processed: #{routine['files_count']}"
  output << "\nFiles changed: #{routine['files_changed'].size}"
  routine['log'].each do |doc|
    output << "\nFile: #{doc[:file]}"
    output << "\nMatches:"
    doc[:matchlog].each do |mch|
      output << "\n#{mch[:matches]}: #{mch[:pattern]}"
    end
  end
  output
end

#load_patterns(pfile) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/subtxt.rb', line 22

def load_patterns pfile
  records = []
  File.open(pfile, "r") do |pats|
    pair = {}
    rowct = 0
    pats.each_line do |row|
      break if row.chomp.downcase == "eof"
      unless pair['fnd'] and pair['rep']
        unless pair['fnd']
          pair['fnd'] = row.chomp
        else
          pair['rep'] = row.chomp
        end
      else
        records << pair
        pair = {}
      end
    end
  end
  return records
end

#subtexts(opts) ⇒ Object



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
82
83
84
85
86
87
88
89
90
# File 'lib/subtxt.rb', line 44

def subtexts opts
  patterns = load_patterns(opts[:patterns])
  @logger.info "Reading patterns from #{@options[:patterns]}"
  routine = {}
  routine['files_count'] = 0
  routine['files_changed'] = []
  routine['files_changed_count'] = 0
  routine['log'] = []
  Dir.glob(opts[:ingestpath]) do |f|
    text = File.read(f)
    @logger.debug "Processing file: #{File.basename(f)}"
    sandr = []
    patterns.each do |rec|
      fnd = rec['fnd']
      rep = rec['rep'].gsub(/\\n/, "\n")
      if opts[:verbose] or opts[:debug]
        matches = text.gsub(/#{fnd}/).count
        syms = text.gsub(/#{fnd}/) {|sym| "-#{sym}-"}
        if matches > 0
          sandr << {:pattern => fnd, :matches => matches, :syms => syms}
          unless routine['files_changed'].include? f
            routine['files_changed'] << f
          end
        end
      end
      text.gsub!(/#{fnd}/, rep)
    end
    if opts[:verbose] or opts[:debug]
      routine['log'] << {:file => f, :matchlog => sandr }
    end
    unless opts[:expext]
      outfile = File.basename f
    else
      fn = File.basename(f,".*")
      outfile = "#{fn}.#{opts[:expext]}"
    end
    begin
      FileUtils::mkdir_p(opts[:expath]) unless File.exists?(opts[:expath])
      File.open("#{opts[:expath]}/#{outfile}", 'w') { |file| file.write(text) }
      @logger.debug "File saved (#{outfile})"
      routine['files_count'] += 1
    rescue Exception => ex
      raise "Failure: #{ex}"
    end
  end
  @logger.info display_results(routine)
end