Class: Less::Engine

Inherits:
String
  • Object
show all
Defined in:
lib/less/engine.rb

Constant Summary collapse

REGEX =
{
  :path     => /([#.][->#.\w ]+)?( ?> ?)?@([-\w]+)/,     # #header > .title > @var
  :selector => /[-\w #.,>*:\(\)]/,                       # .cow .milk > a
  :variable => /@([-\w]+)/,                              # @milk-white
  :property => /@[-\w]+|[-a-z]+/,                        # font-size
  :color    => /#([a-zA-Z0-9]{3,6})\b/,                  # #f0f0f0
  :number   => /\d+(?>\.\d+)?/,                          # 24.8
  :unit     => /px|em|pt|cm|mm|%/                        # em
}

Instance Method Summary collapse

Constructor Details

#initialize(s) ⇒ Engine

Returns a new instance of Engine.



15
16
17
18
# File 'lib/less/engine.rb', line 15

def initialize s
  super
  @tree = Tree.new self.hashify
end

Instance Method Details

#compileObject Also known as: render



20
21
22
23
24
25
26
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
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/less/engine.rb', line 20

def compile     
  #
  # Parse the variables and mixins
  #
  # We use symbolic keys, such as :mixins, to store LESS-only data,
  # each branch has its own :mixins => [], and :variables => {}
  # Once a declaration has been recognised as LESS-specific, it is copied 
  # in the appropriate data structure in that branch. The declaration itself
  # can then be deleted.
  #
  @tree = @tree.traverse :leaf do |key, value, path, node|
    matched = if match = key.match( REGEX[:variable] )          
      node[:variables] ||= Tree.new
      node[:variables][ match.captures.first ] = value
    elsif value == :mixin
      node[:mixins] ||= []          
      node[:mixins] << key
    end
    node.delete key if matched # Delete the property if it's LESS-specific
  end
  
  #
  # Evaluate mixins
  #
  @tree = @tree.traverse :branch do |path, node|
    if node.include? :mixins
      node[:mixins].each do |m|
        @tree.find( :mixin, m.delete(' ').split('>') ).each {|k, v| node[ k ] = v }
      end
    end
  end
  
  # Call `evaluate` on variables, such as '@dark: @light / 2'
  @tree = @tree.traverse :branch do |path, node|
    node.vars.each do |key, value|
      evaluate key, value, node.vars
    end if node.vars?
  end
  
  # Call `evaluate` on css properties, such as 'font-size: @big'
  @tree = @tree.traverse :leaf do |key, value, path, node|
    evaluate key, value, node
  end
  
  #
  # Evaluate operations (2+2)
  #
  # Units are: 1px, 1em, 1%, #111
  @tree = @tree.traverse :leaf do |key, value, path, node| 
    node[ key ] = value.gsub /(#{REGEX[:operand]}(\s?)[-+\/*](\4))+(#{REGEX[:operand]})/ do |operation|
      if (unit = operation.scan(/#{REGEX[:numeric]}|(#)/i).flatten.compact.uniq).size <= 1
        unit = unit.join            
        operation = if unit == '#'
          evaluate = lambda do |v| 
            result = eval v
            unit + ( result.zero?? '000' : result.to_s(16) )
          end
          operation.gsub REGEX[:color] do
            hex = $1 * ( $1.size < 6 ? 6 / $1.size : 1 )
            hex.to_i(16)
          end.delete unit
        else
          evaluate = lambda {|v| eval( v ).to_s + unit }
          operation.gsub REGEX[:unit], ''
        end.to_s                
        next if operation.match /[a-z]/i
        evaluate.call operation
      else
        raise MixedUnitsError
      end
    end
  end
end

#evaluate(key, value, node) ⇒ Object

Evaluate variables



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/less/engine.rb', line 98

def evaluate key, value, node               
  if value.is_a? String and value.include? '@'       # There's a var to evaluate    
    value.scan REGEX[:path] do |p|
      p = p.join.delete ' '
      var = if p.include? '>'
        @tree.find :var, p.split('>')                # Try finding it in a specific namespace
      else
        node.var( p ) || @tree.var( p )              # Try local first, then global
      end

      if var
        node[ key ] = value.gsub REGEX[:path], var   # Substitute variable with value
      else
        node.delete key                              # Discard the declaration if the variable wasn't found
      end
    end    
  end
end

#hashifyObject



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/less/engine.rb', line 121

def hashify
#
# Parse the LESS structure into a hash
#
###
  #   less:     color: black;
  #   hashify: "color" => "black"
  #
  hash = self.gsub(/\t/, ' ').                                                        # Tabs
              gsub(/\r\n/, "\n").                                                     # m$
              gsub(/\/\/.*/, '').                                                     # Comments //
              gsub(/\/\*.*?\*\//m, '').                                               # Comments /*
              gsub(/"/, "'").                                                         # " => '
              gsub(/("|')(.+?)(\1)/) { $1 + CGI.escape( $2 ) + $1 }.                  # Escape string values
              gsub(/(#{REGEX[:property]}):\s*(.+?)\s*(;|(?=\}))/,'"\1"=>"\2",').      # Rules
              gsub(/\}/, "},").                                                       # Closing }
              gsub(/( *)(#{REGEX[:selector]}+?)[ \n]*(?=\{)/m, '\1"\2"=>').           # Selectors
              gsub(/([.#][->\w .#]+);/, '"\\1" => :mixin,')                           # Mixins
  eval "{" + hash + "}"                                                               # Return {hash}
end

#to_cssObject



117
118
119
# File 'lib/less/engine.rb', line 117

def to_css
  self.compile.to_css
end