Class: Goliath::Rack::Formatters::HTML

Inherits:
Object
  • Object
show all
Includes:
AsyncMiddleware
Defined in:
lib/goliath/rack/formatters/html.rb

Overview

A simple HTML formatter. This doesn’t try to be fancy and just turns Hashes into tables, Arrays into ordered lists and strings are output as HTML escaped strings.

Examples:

use Goliath::Rack::Formatters::HTML

Instance Method Summary collapse

Methods included from AsyncMiddleware

#call, #final_response?, #hook_into_callback_chain, #initialize

Methods included from Validator

safely, validation_error

Instance Method Details

#array_to_html(content) ⇒ Object



57
58
59
60
61
62
# File 'lib/goliath/rack/formatters/html.rb', line 57

def array_to_html(content)
  html_string = '<ol>\n'
  content.each { |value| html_string += "<li>#{to_html(value)}</li>\n" }
  html_string +="</ol>\n"
  html_string
end

#hash_to_html(content) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/goliath/rack/formatters/html.rb', line 43

def hash_to_html(content)
  html_string = "<table>\n"
  if content.key?('meta')
    html_string += "<tr><td>meta</td><td>\n"
    html_string += to_html(content['meta'])
    html_string += "</td></tr>\n"
    content.delete('meta')
  end

  content.each_pair { |key, value| html_string += "<tr><td>#{to_html(key)}</td><td>#{to_html(value)}</td></tr>\n" }
  html_string += "</table>\n"
  html_string
end


68
69
70
# File 'lib/goliath/rack/formatters/html.rb', line 68

def html_footer
  "</body></html>"
end

#html_headerObject



64
65
66
# File 'lib/goliath/rack/formatters/html.rb', line 64

def html_header
  "<html><body>"
end

#html_response?(headers) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/goliath/rack/formatters/html.rb', line 20

def html_response?(headers)
  headers['Content-Type'] =~ %r{^text/html}
end

#post_process(env, status, headers, body) ⇒ Object



15
16
17
18
# File 'lib/goliath/rack/formatters/html.rb', line 15

def post_process(env, status, headers, body)
  body = [to_html(body, false)] if html_response?(headers)
  [status, headers, body]
end

#string_to_html(content) ⇒ Object



39
40
41
# File 'lib/goliath/rack/formatters/html.rb', line 39

def string_to_html(content)
  ::Rack::Utils.escape_html(content.to_s)
end

#to_html(content, fragment = true) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/goliath/rack/formatters/html.rb', line 24

def to_html(content, fragment=true)
  html_string = ''
  html_string += html_header unless fragment

  html_string += case(content.class.to_s)
  when "Hash" then hash_to_html(content)
  when "Array" then array_to_html(content)
  when "String" then string_to_html(content)
  else string_to_html(content)
  end

  html_string += html_footer unless fragment
  html_string
end