Class: Less::Tree

Inherits:
Hash
  • Object
show all
Defined in:
lib/less/tree.rb

Instance Method Summary collapse

Methods inherited from Hash

#to_tree

Constructor Details

#initialize(init = {}) ⇒ Tree

Returns a new instance of Tree.



3
4
5
# File 'lib/less/tree.rb', line 3

def initialize init = {}  
  self.replace init
end

Instance Method Details

#find(what = :var, path = []) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/less/tree.rb', line 19

def find what = :var, path = []
  path.inject(self) do |branch, k|        
    if what == :var && k == path.last
      branch[:variables][ k ]
    else
      branch = branch[ k ]
    end
  end
end

#to_css(css = []) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/less/tree.rb', line 57

def to_css css = []
  self.traverse :branch do |path, node|
    properties = node.inject("") do |s, (k, v)|          
      v.is_a?(String) ? (s + "#{k}: #{v}; ") : s   # Add the property to the list
    end
    css << path * ' > ' + " { " + properties + "}" # Add the rule-set to the CSS
  end
  css.join "\n"
end

#traverse(by = :leaf, path = [], &blk) ⇒ Object



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
# File 'lib/less/tree.rb', line 29

def traverse by = :leaf, path = [], &blk
#
# Traverse the whole tree, returning each leaf or branch (recursive)
#
###
  #   Aside from the key & value, 
  #   we yield the full path of the leaf, aswell as
  #   the branch which contains it (self).
  #
  self.each do |key, value|                        # `self` is the current node, starting with the trunk
    if value.is_a? Hash and key != :variables      # If the node is a branch, we can go deeper
      path << key                                  # Add the current branch to the path
      self[ key ] = value.to_tree.                 # Make sure any change is saved to the main tree
                    traverse by, path, &blk        # Recurse, with the current node becoming `self`
      if by == :branch             
        yield path, self[ key ]                    # The node is a branch, yield it to the block
        path.pop
      end
    elsif by == :leaf and key.is_a? String
      yield key, value, path, self                 # The node is a leaf, yield it to the block
      path.pop
    else
      next
    end
  end
  self
end

#var(k) ⇒ Object



7
8
9
# File 'lib/less/tree.rb', line 7

def var k
  self[:variables] ? self[:variables][ k ] : nil
end

#varsObject



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

def vars
  self[:variables] ? self[:variables] : nil
end

#vars?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/less/tree.rb', line 11

def vars?
  self.include? :variables
end