Class: Rack::CoffeeFilter::Filter

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-coffee_filter/filter.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, wrap_js = false) ⇒ Filter

Returns a new instance of Filter.



6
7
8
9
# File 'lib/rack-coffee_filter/filter.rb', line 6

def initialize(app, wrap_js = false)
  @wrap_js = wrap_js
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
# File 'lib/rack-coffee_filter/filter.rb', line 29

def call(env)
  env['PATH_INFO'].match(/\.coffee$/) ? filtered_response(env) : @app.call(env)
end

#filtered_response(env) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rack-coffee_filter/filter.rb', line 11

def filtered_response(env)
  status, headers, response = @app.call(env)

  return @app.call(env) if !(200..299).cover?(status)

  response_body = ''
  response.each { |part| response_body += part }

  js = ::CoffeeScript.compile(response_body, { bare: !@wrap_js })

  headers['Content-Length'] = js.length.to_s
  headers['Content-Type'] = 'application/javascript;charset=utf-8'
  headers['Cache-Control'] = 'private, max-age=0, must-revalidate'
  headers['Last-Modified'] = Time.now.to_s

  [200, headers, [js]]
end