Class: Smarky::Element

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

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Element

Returns a new instance of Element.



3
4
5
6
7
8
9
10
11
12
13
14
15
# 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

Instance Method Details

#[]=(attribute, value) ⇒ Object



40
41
42
# File 'lib/smarky/element.rb', line 40

def []=(attribute, value)
  @node[attribute] = value
end

#add_child(child) ⇒ Object



56
57
58
59
60
# File 'lib/smarky/element.rb', line 56

def add_child(child)
  @node.add_child(child.node)
  dirty!
  child
end

#add_next_sibling(sibling) ⇒ Object



62
63
64
65
66
# File 'lib/smarky/element.rb', line 62

def add_next_sibling(sibling)
  @node.add_next_sibling(sibling.node)
  dirty!
  sibling
end

#add_sectionObject



68
69
70
# File 'lib/smarky/element.rb', line 68

def add_section
  add_child(Element.new('section'))
end

#attributesObject



36
37
38
# File 'lib/smarky/element.rb', line 36

def attributes
  @node.attributes
end

#childrenObject



48
49
50
# File 'lib/smarky/element.rb', line 48

def children
  @children ||= @node.children.map { |node| Element.new(node) }
end

#contentObject



44
45
46
# File 'lib/smarky/element.rb', line 44

def content
  @node.content
end

#inner_htmlObject



88
89
90
# File 'lib/smarky/element.rb', line 88

def inner_html
  @node.inner_html
end

#nameObject



28
29
30
# File 'lib/smarky/element.rb', line 28

def name
  @node.name
end

#name=(value) ⇒ Object



32
33
34
# File 'lib/smarky/element.rb', line 32

def name=(value)
  @node.name = value
end

#parentObject



24
25
26
# File 'lib/smarky/element.rb', line 24

def parent
  @parent ||= Element.new(@node.parent)
end

#sectionsObject



52
53
54
# File 'lib/smarky/element.rb', line 52

def sections
  @sections ||= @node.css('> section').map { |node| Element.new(node) }
end

#titleObject



17
18
19
20
21
22
# 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 = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# 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