Class: Texta::T

Inherits:
String show all
Defined in:
lib/texta.rb

Instance Method Summary collapse

Methods included from StringAdapter

#texta

Constructor Details

#initialize(html) ⇒ T

Returns a new instance of T.



42
43
44
45
# File 'lib/texta.rb', line 42

def initialize(html)
  body = Nokogiri.HTML(html).css("body").first
  super children(body).join("\n")
end

Instance Method Details

#children(node) ⇒ Object



47
48
49
50
51
# File 'lib/texta.rb', line 47

def children(node)
  nodes = node.children.map do |n|
    process(n)
  end.compact
end

#process(node) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/texta.rb', line 53

def process(node)
  case node.name
  when "meta", "link", "style"
    ""
    
  # bold
  when "b", "strong"
    "**" + children(node).join(" ") + "**"
  # italic
  when "i", "em"
    "_" + children(node).join(" ") + "_"
  # plain
  when "u", "span", "font"
    children(node).join(" ")
  when "p", "div"
    children(node).join(" ") + "\n"
  when "br"
    "\n"

  # links
  when "a"
    return ""
    return "" unless node["href"]
    "[" + children(node).join(" ") + "]" + "(" + node["href"] + ")"

  # headlines
  when /h([1-2])/
    char = $1 == "1" ? "=" : "-"
    s = children(node).join(" ")
    "#{s}\n" + char * [ [s.length, 6].min, 32 ].max + "\n\n"
  when /h([1-6])/   
    "#" * $1.to_i + " " + children(node).join(" ") + "\n\n"
  
  # images
  
  when "img"
    alt = node["alt"]
    alt = nil if alt == ""
    alt = node["title"] if !alt

    if alt && alt != ""
      "[#{alt}]"
    end
    
  # text nodes

  when "text"
    s = node.to_s.gsub(/(^\s+)|(\s+$)/, "")
    s == "" ? nil : s 
  
  # tables
  
  when "table"
    children(node).join("")
  when "tr"
    children(node).join(" ") + "\n"
  when "th"
    "**" + children(node).join(" ") + "**"
  when "td"
    children(node).join(" ")

  # lists

  when "ul"
    children(node).map { |s| "- #{s}\n" }.join + "\n"
  when "li"
    children(node).join(" ")

  when "comment"
    ""
  else
    raise Error, "node <#{node.name}>"
  end
end