Class: Jsonview::Middleware
- Inherits:
-
Object
- Object
- Jsonview::Middleware
- Defined in:
- lib/jsonview/middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
- #encode(string) ⇒ Object
- #html_document(value) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
- #represent(value) ⇒ Object
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
3 4 5 |
# File 'lib/jsonview/middleware.rb', line 3 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/jsonview/middleware.rb', line 7 def call(env) response = @app.call(env) accept = env['HTTP_ACCEPT'] || '' if accept =~ /html/ && !(accept =~ /json/) status, headers, body = response content_type = headers['Content-Type'] || '' if content_type =~ /json/ json = body.to_enum(:each).to_a.join html = html_document(JSON.parse(json)) headers['Content-Type'] = "text/html;charset=utf-8" headers['Content-Length'] = html.bytesize.to_s response = [status, headers, [html]] end end response end |
#encode(string) ⇒ Object
104 105 106 |
# File 'lib/jsonview/middleware.rb', line 104 def encode(string) string.gsub /[<>&"]/, '<' => '<', '>' => '>', '&' => '&', '"' => '\"' end |
#html_document(value) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/jsonview/middleware.rb', line 27 def html_document(value) <<-HTML <!DOCTYPE html> <html> <head> <style> null { color: red } string { color: green } number, boolean { color: blue } unknown { color: gray } hash, array { display: block; margin-left: 2em } key { font-weight: bold } </style> </head> <body> #{represent(value).join} </body> </html> HTML end |
#represent(value) ⇒ Object
48 49 50 51 52 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 |
# File 'lib/jsonview/middleware.rb', line 48 def represent(value) case value when nil "<null>null</null>" when Numeric "<number>#{value}</number>" when TrueClass, FalseClass "<boolean>#{value}</boolean>" when Array [ "[<array>\n", value.each_with_index.map do |v, i| [ (",<br/>\n" if i > 0), represent(v), ] end, "\n</array>]", ] when Hash [ "{<hash>\n", value.each_with_index.map do |(k, v), i| [ (",<br/>\n" if i > 0), "<key>"", encode(k.to_s), ""</key>: ", represent(v), ] end, "\n</hash>}", ] when URI.regexp(%w[http https]) [ ""<a href=\"", encode(value), "\">", encode(value), "</a>"", ] when String [ "<string>"", encode(value), ""</string>", ] else [ "<unknown>"", encode(value.inspect), ""</unknown>", ] end end |