class Glam::Glamorizer
Constants
- VOID_ELEMENTS
Attributes
current_indent[RW]
indent_char[RW]
indent_size[RW]
Public Class Methods
new(opts={})
click to toggle source
@param opts [Hash] The options @option opts [Integer] :indent_size
How many spaces should be used for each level of indentation
# File lib/glam/glamorizer.rb, line 13 def initialize(opts={}) self.indent_size = 2 self.indent_char = ' ' self.current_indent = 0 if opts opts.each do |k,v| send("#{k}=", v) end end end
Public Instance Methods
glamorize(html)
click to toggle source
Pretty-print the HTML @param html [String] The HTML to be pretty-printed @return [String] The pretty-printed HTML
# File lib/glam/glamorizer.rb, line 28 def glamorize(html) node = if html.is_a?(Nokogiri::XML::Node) result = '' html else result = "<!doctype html>" Nokogiri::HTML(html).root end result << indented_node_with_attributes(node) if node.children.size == 1 and node.children.first.text? child_node = node.children.first result << "#{child_node.content.strip}</#{node.name}>" else self.current_indent += 1 node.children.each do |child_node| if child_node.text? unless child_node.blank? result << "\n#{indent}#{child_node.content.strip}" end elsif child_node.comment? result << "\n#{indent}<!-- #{child_node.content.strip} -->" elsif VOID_ELEMENTS.include?(child_node.name) result << "\n#{indented_node_with_attributes(child_node)}" else result << glamorize(child_node) end end self.current_indent -= 1 if current_indent < 1 result << "\n#{indent}</#{node.name}>\n" else result << "\n#{indent}</#{node.name}>" end end end
Private Instance Methods
indent()
click to toggle source
# File lib/glam/glamorizer.rb, line 66 def indent indent_char * (indent_size * current_indent) end
indented_node_with_attributes(node)
click to toggle source
# File lib/glam/glamorizer.rb, line 70 def indented_node_with_attributes(node) "\n#{indent}<#{node.name}#{node.attributes.map{|n,v| %{ #{n}="#{v}"}}.join}>" end