Class: LessReplacer

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

Constant Summary collapse

VAR_PATTERN =
/(@[a-z\-]+):\s*([^;]*);(.*)/
LENGTH_PATTERN =
/(\s+|:)([0-9\.]+(em|px|));/
COLOR_PATTERN =
/()(#[a-fA-F0-9]+);/

Instance Method Summary collapse

Constructor Details

#initializeLessReplacer



11
12
13
14
15
16
# File 'lib/lessFactor.rb', line 11

def initialize
  @vars = {}
  @literals = {}
  @literalcomments = {}
  @occurence = {}
end

Instance Method Details

#replace_vars(infile, outfile) ⇒ Object



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
# File 'lib/lessFactor.rb', line 52

def replace_vars(infile, outfile)
  result = File.open(infile, "r").readlines.each.map { |l|
    r1 = l.gsub(LENGTH_PATTERN) do |m|
      vn =$2.downcase
      if  @literals[vn]
        name = @literals[vn].join("__")
        $1 + name +';'
      else
        m
      end
    end

    r1.gsub(COLOR_PATTERN) do |m|
      vn =$2.downcase
      if  @literals[vn]
        name = @literals[vn].join("__")
        $1 + name +';'
      else
        m
      end
    end
  }

  File.open(outfile, "w") do |f|
    f.puts(result.join())
  end
end

#save_vars(file) ⇒ Object



81
82
83
84
85
86
87
88
89
90
# File 'lib/lessFactor.rb', line 81

def save_vars(file)
  File.open(file, "w") do |f|
    @literals.sort { |a, b| a[1] <=> b[1] }.each { |value, name|
      the_name = name.first
      occurrences = @literalcomments[value] || []
      comment = @vars[the_name] || {c: " // todo: #{occurrences.count}: #{occurrences}"}
      f.printf "%-25s %-15s %s\n", "#{the_name}:", " #{value};", comment[:c]
    }
  end
end

#scan_literals(file) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/lessFactor.rb', line 28

def scan_literals(file)
  line = 0
  File.open(file, "r").readlines.each do |l|

    line +=1

    l.match(LENGTH_PATTERN) do |m|
      value =$2.downcase
      unless @literals[value]
        (@literals[value] ||= []).push "@zz-size-" + "000#{@literals.keys.count}"[-3 .. -1]
      end
      (@literalcomments[value] ||= []).push line
    end

    l.match(COLOR_PATTERN) do |m|
      value =$2.downcase
      unless @literals[value]
        (@literals[value] ||= []).push "@zz-color-" + "000#{@literals.keys.count}"[-3 .. -1]
      end
      (@literalcomments[value] ||= []).push line
    end
  end
end

#scan_vars(file) ⇒ Object



18
19
20
21
22
23
24
25
26
# File 'lib/lessFactor.rb', line 18

def scan_vars(file)
  File.open(file, "r").readlines.each do |l|
    l.match(VAR_PATTERN) do |m|
      value =$2.downcase
      @vars[$1] = {v: value, c: $3}
      (@literals[value] ||= []).push $1
    end
  end
end