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



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

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

#add_child(child) ⇒ Object



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

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

#add_next_sibling(sibling) ⇒ Object



58
59
60
61
62
# File 'lib/smarky/element.rb', line 58

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

#add_sectionObject



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

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

#attributesObject



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

def attributes
  @node.attributes
end

#childrenObject



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

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

#contentObject



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

def content
  @node.content
end

#inner_htmlObject



72
73
74
# File 'lib/smarky/element.rb', line 72

def inner_html
  @node.inner_html
end

#nameObject



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

def name
  @node.name
end

#parentObject



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

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

#sectionsObject



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

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_htmlObject



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

def to_html
  @node.to_html
end