Class: Colora::Data

Inherits:
Object
  • Object
show all
Defined in:
lib/colora/data.rb

Constant Summary collapse

SPLIT =
lambda do |line|
  flag = line[0]
  code, pounds, comment = line[1..].split(/(?<!['"])(\s*#+)(?!{)/, 2)
  code = nil if code.empty?
  comment ? [flag, code, pounds+comment] : [flag, code, nil]
end
UPDATE =
lambda do |hash, key, flag|
  k = key.strip
  hash[k] = case hash[k]
            when nil
                flag # added(+>) or removed(-<)
            when 'd', 't', flag
                'd' # duplicate
            else
                't' # touched
            end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lines) ⇒ Data

Returns a new instance of Data.



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/colora/data.rb', line 40

def initialize(lines)
  @lines,@codes,@comments,@edits = [],{},{},Set.new
  while (line = lines.shift)
    @lines << pre_process(line)
  end
  populate_edits
  @lines.each do |line|
    next unless line.is_a?(Array)
    post_process line
  end
  @codes = @comments = @edits = nil # GC
end

Instance Attribute Details

#linesObject (readonly)

Returns the value of attribute lines.



38
39
40
# File 'lib/colora/data.rb', line 38

def lines
  @lines
end

Instance Method Details

#populate_editsObject



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

def populate_edits
  partners = []
  jarrow = FuzzyStringMatch::JaroWinkler.create(:pure) # Need pure for UTF-8
  removed = @codes.select{|_,flag| '-<'.include?flag}.keys
  added   = @codes.select{|_,flag| '+>'.include?flag}.keys
  short, long = [removed, added].sort_by(&:length)
  short.each do |a|
    long.each do |b|
      d = jarrow.getDistance(a, b)
      partners.push([a, b, d]) if d > 0.618034
    end
  end
  partners.sort_by(&:last).reverse.each do |a, b, _|
    next if @edits.include?(a) || @edits.include?(b)
    @edits.add(a)
    @edits.add(b)
  end
end

#post_process(line) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/colora/data.rb', line 72

def post_process(line)
  if (code = line[1]&.strip)
    flag = @edits.include?(code) ? 'e' : @codes[code]
    line[1] = [flag, line[1]]
  end
  if (comment = line[2]&.strip)
    flag = @comments[comment]
    line[2] = [flag, line[2]]
  end
end

#pre_process(line) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/colora/data.rb', line 21

def pre_process(line)
  # rubocop:disable Lint/DuplicateBranch
  case line.rstrip
  when '', '+', '-', '---', /^[-+][-+][-+] [ab]/
    line
  when /^[-+<>]/
    flag, code, comment = SPLIT[line]
    f = flag=='-' ? '<' : flag=='+' ? '>' : flag
    UPDATE[@codes, code, f] if code
    UPDATE[@comments, comment, f] if comment
    [flag, code, comment]
  else
    line
  end
  # rubocop:enable Lint/DuplicateBranch
end