Class: GridSizeDisplay::Rack

Inherits:
Object
  • Object
show all
Defined in:
lib/grid_size_display/engine.rb

Constant Summary collapse

DEFAULT_INSERTION_POINT =
'</body>'.freeze
HTML_CONTENT_TYPE =
'text/html'.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Rack

Returns a new instance of Rack.



15
16
17
18
# File 'lib/grid_size_display/engine.rb', line 15

def initialize(app, options = {})
  @app, @options = app, options
  @options[:insertion_point] ||= DEFAULT_INSERTION_POINT
end

Instance Method Details

#call(env) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/grid_size_display/engine.rb', line 20

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

  req = process_display_param(env)

  if headers['Content-Type'].to_s.include?(HTML_CONTENT_TYPE) && display_grid?(req)
    new_response = []
    response.each do |body|
      # find the last matching insertion point in the body and insert the content
      partition = body.rpartition(@options[:insertion_point])
      partition[0] += %q{<div id="grid-size-display-container"></div>}
      new_response << partition.join
    end

    # Update the content-length
    headers['Content-Length'] = new_response.inject(0) do |len, body|
      len += body.bytesize
    end.to_s

    [status, headers, new_response]
  else
    [status, headers, response]
  end
end

#display_grid?(req) ⇒ Boolean

Returns:

  • (Boolean)


45
46
47
# File 'lib/grid_size_display/engine.rb', line 45

def display_grid?(req)
  ::GridSizeDisplay.config.enabled? && req.session['grid_size_display']
end

#process_display_param(env) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/grid_size_display/engine.rb', line 50

def process_display_param(env)
  req = ::Rack::Request.new(env)

  case req.params['grid_size_display']
  when 'enable' then req.session['grid_size_display'] = true
  when 'disable' then req.session['grid_size_display'] = false
  end

  req.session['grid_size_display'] = true if req.session['grid_size_display'].nil?
  req
end