Class: HamlInterceptor
- Inherits:
-
Object
- Object
- HamlInterceptor
- Defined in:
- lib/haml_interceptor.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, opts = {}) ⇒ HamlInterceptor
constructor
A new instance of HamlInterceptor.
- #js_response?(env, headers) ⇒ Boolean
- #parse(body, json = true) ⇒ Object
Constructor Details
#initialize(app, opts = {}) ⇒ HamlInterceptor
Returns a new instance of HamlInterceptor.
4 5 6 |
# File 'lib/haml_interceptor.rb', line 4 def initialize(app, opts={}) @app = app end |
Instance Method Details
#call(env) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 |
# File 'lib/haml_interceptor.rb', line 8 def call(env) status, headers, resp = @app.call(env) body = if resp.respond_to?(:body) resp.body.respond_to?(:join) ? resp.body.join : resp.body else resp end if js_response?(env, headers) body = parse(body) end [status, headers, body] end |
#js_response?(env, headers) ⇒ Boolean
22 23 24 |
# File 'lib/haml_interceptor.rb', line 22 def js_response?(env, headers) env['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' || (headers.has_key?('Content-Type') && headers['Content-Type'] =~ /javascript/) end |
#parse(body, json = true) ⇒ Object
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/haml_interceptor.rb', line 26 def parse(body, json = true) parsed = json ? (JSON.parse(body) rescue body) : body if parsed.respond_to?(:values) parsed.keys.each do |key| parsed[key] = parse(parsed[key], false) end else parsed = Haml::HTML.new(parsed).render end json ? (JSON.generate(parsed) rescue parsed) : parsed end |