Class: HtmlToTextile::Document

Inherits:
Nokogiri::XML::SAX::Document
  • Object
show all
Defined in:
lib/html_to_textile.rb

Instance Method Summary collapse

Instance Method Details

#characters(string) ⇒ Object



45
46
47
48
49
50
51
# File 'lib/html_to_textile.rb', line 45

def characters string
  if stack.last.nil? or stack.last['content'].nil?
    stack << "#{string}"
  else
    stack.last['content'] << "#{string}"
  end
end

#end_element(name) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/html_to_textile.rb', line 34

def end_element name
  if valid_tags.include? name
    content = stack.pop
    if stack.empty? or stack.last['content'].nil?
      tree << content
    else
      stack.last['content'] << content
    end
  end
end

#stackObject



13
14
15
# File 'lib/html_to_textile.rb', line 13

def stack
  @stack ||= []
end

#start_element(name, attrs = []) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/html_to_textile.rb', line 17

def start_element name, attrs = []
  if valid_tags.include? name
    attrs_hash = {}
    while key = attrs.shift do
      value = attrs.shift
      attrs_hash[key] = value
    end
    
    
    stack << {
      'name' => name, 
      'content' => [],
      'attrs' => attrs_hash
    }
  end
end

#to_htmlObject



73
74
75
76
77
78
79
# File 'lib/html_to_textile.rb', line 73

def to_html
  @html = ''
  tree.each do |content|
    _to_html_tag content
  end
  return @html
end

#to_textileObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/html_to_textile.rb', line 53

def to_textile  
  ##ActiveRecord::Base.logger.debug  "### tree START"
  ##ActiveRecord::Base.logger.debug  @tree.inspect
  ##ActiveRecord::Base.logger.debug  "### tree END"
  #ActiveRecord::Base.logger.debug  "### HTML START"
  to_html
  #ActiveRecord::Base.logger.debug  "### HTML END"
  
  textile = ''
  tree.each do |content|
    textile += _to_textile_tag content
  end
  
  #ActiveRecord::Base.logger.debug  "### TEXTILE START"
  #ActiveRecord::Base.logger.debug  textile
  #ActiveRecord::Base.logger.debug  "### TEXTILE END"      
  
  return textile
end

#treeObject



9
10
11
# File 'lib/html_to_textile.rb', line 9

def tree
  @tree ||= []
end

#valid_tagsObject



5
6
7
# File 'lib/html_to_textile.rb', line 5

def valid_tags
  ['a','p','br','u','b','i','strong','em','ul','ol','li','sup','sub', 'ins', 'del', 'h1', 'h2', 'h3', 'table', 'tr', 'td', 'th']
end