class Smarky::Element

Public Class Methods

new(*args) click to toggle source
# File lib/smarky/element.rb, line 3
def initialize(*args)
  node_or_name, @title = args

  case node_or_name
  when String
    @document = Nokogiri::HTML::Document.new
    @node     = Nokogiri::XML::Node.new(node_or_name, @document)

  else
    @document = node_or_name.document
    @node     = node_or_name
  end
end

Public Instance Methods

[]=(attribute, value) click to toggle source
# File lib/smarky/element.rb, line 40
def []=(attribute, value)
  @node[attribute] = value
end
add_child(child) click to toggle source
# File lib/smarky/element.rb, line 56
def add_child(child)
  @node.add_child(child.node)
  dirty!
  child
end
add_next_sibling(sibling) click to toggle source
# File lib/smarky/element.rb, line 62
def add_next_sibling(sibling)
  @node.add_next_sibling(sibling.node)
  dirty!
  sibling
end
add_section() click to toggle source
# File lib/smarky/element.rb, line 68
def add_section
  add_child(Element.new('section'))
end
attributes() click to toggle source
# File lib/smarky/element.rb, line 36
def attributes
  @node.attributes
end
children() click to toggle source
# File lib/smarky/element.rb, line 48
def children
  @children ||= @node.children.map { |node| Element.new(node) }
end
content() click to toggle source
# File lib/smarky/element.rb, line 44
def content
  @node.content
end
inner_html() click to toggle source
# File lib/smarky/element.rb, line 88
def inner_html
  @node.inner_html
end
name() click to toggle source
# File lib/smarky/element.rb, line 28
def name
  @node.name
end
name=(value) click to toggle source
# File lib/smarky/element.rb, line 32
def name=(value)
  @node.name = value
end
parent() click to toggle source
# File lib/smarky/element.rb, line 24
def parent
  @parent ||= Element.new(@node.parent)
end
sections() click to toggle source
# File lib/smarky/element.rb, line 52
def sections
  @sections ||= @node.css('> section').map { |node| Element.new(node) }
end
title() click to toggle source
# File lib/smarky/element.rb, line 17
def title
  @title ||= begin
    first_child = @node.children.first
    first_child && first_child.name =~ /^h[1-6]$/ && first_child.content
  end
end
to_html(options={}) click to toggle source
# File lib/smarky/element.rb, line 72
def to_html(options={})
  node = @node

  if options[:omit_titles]
    node = node.clone
    node.css('h1,h2,h3,h4,h5,h6').each do |child|
      child.remove()
    end
  end

  # Getting nicely indented HTML:
  # http://stackoverflow.com/questions/1898829/how-do-i-pretty-print-html-with-nokogiri
  # This might be a huge mistake?
  node.to_xhtml(:indent => 2, :indent_text => ' ')
end

Protected Instance Methods

node() click to toggle source
# File lib/smarky/element.rb, line 94
def node
  @node
end

Private Instance Methods

dirty!() click to toggle source
# File lib/smarky/element.rb, line 100
def dirty!
  @title    = nil
  @parent   = nil
  @children = nil
  @sections = nil
end