Class: BemHtml

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

Class Method Summary collapse

Class Method Details

.parse(content) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
# File 'lib/bem_html.rb', line 5

def self.parse(content)
	html_doc = Nokogiri::HTML(content)
	html_doc.xpath('.//*[@bem-block]|*[@bem-block]').each do |blockNode|
		currentBlock = blockNode["bem-block"]
		blockNode.attributes["bem-block"].remove
		if(not blockNode['class'])
			blockNode['class'] = ""
		end
		blockNode['class'] += " #{currentBlock}"
		nextBlock = [currentBlock]
		if(blockNode.attributes["bem-modifiers"])
			JSON.parse(blockNode.attributes["bem-modifiers"].value.gsub(/\:(\w+)/,'"\1"')).each do |modifier|
				nextBlock.push("#{currentBlock}--#{modifier}")
				blockNode['class'] += " #{currentBlock}--#{modifier}"
			end
			blockNode.attributes["bem-modifiers"].remove
		end
		processingQueue = [[nextBlock, blockNode.children]]
		while processingQueue.length > 0
			topQueue = processingQueue.shift
			currentBlock = topQueue[0]
			nodes = topQueue[1]
			nodes.each do |node|
				next if not node.attributes
				next if node.attributes["bem-block"]
				next if not node.attributes["bem-element"]
			
				if(not node['class'])
					node['class'] = ""
				end
			
				element = node.attributes["bem-element"]
				node.attributes["bem-element"].remove
				if(currentBlock.respond_to? :push)
					nextBlock = currentBlock.map do |cb|
						node['class'] += " #{cb}__#{element}"
						"#{cb}__#{element}"
					end
				else
					nextBlock = "#{currentBlock}__#{element}"
					node['class'] += " #{nextBlock}"
				end
			
				if(node.attributes["bem-modifiers"])
					JSON.parse(node.attributes["bem-modifiers"].value.gsub(/\:(\w+)/,'"\1"')).each do |modifier|
						if(currentBlock.respond_to? :push)
							currentBlock.each do |cb|
								node['class'] += " #{cb}__#{element}--#{modifier}"
								nextBlock.push("#{cb}__#{element}--#{modifier}")
							end
						else
							node['class'] += " #{currentBlock}__#{element}--#{modifier}"
						end
					end
					node.attributes["bem-modifiers"].remove
				end
				if(node.children.length > 0)
					processingQueue.push([nextBlock, node.children])
				end
			end
		end
	end
	html_doc.to_s
end