Class: Shack::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/shack/middleware.rb

Constant Summary collapse

HEADER_NAME =
"X-Shack-Sha".freeze

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, sha = "") ⇒ Middleware

Returns a new instance of Middleware.



5
6
7
8
# File 'lib/shack/middleware.rb', line 5

def initialize(app, sha = "")
  @app = app
  @sha = sha unless (sha || "").empty?
end

Class Attribute Details

.contentObject

Returns the value of attribute content.



48
49
50
# File 'lib/shack/middleware.rb', line 48

def content
  @content
end

.hide_stampObject

Returns the value of attribute hide_stamp.



48
49
50
# File 'lib/shack/middleware.rb', line 48

def hide_stamp
  @hide_stamp
end

.shaObject

Returns the value of attribute sha.



48
49
50
# File 'lib/shack/middleware.rb', line 48

def sha
  @sha
end

Class Method Details

.configure(&block) ⇒ Object



50
51
52
# File 'lib/shack/middleware.rb', line 50

def configure(&block)
  block.call(self)
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
# File 'lib/shack/middleware.rb', line 10

def call(env)
  status, headers, body = @app.call(env)
  return [status, headers, body] unless sha
  headers[HEADER_NAME] = sha

  if result = inject_stamp(status, headers, body)
    result
  else
    [status, headers, body]
  end
end

#inject_stamp(status, headers, body) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/shack/middleware.rb', line 22

def inject_stamp(status, headers, body)
  return nil if !!self.class.hide_stamp
  return nil unless Stamp.stampable?(headers)
  response = Rack::Response.new([], status, headers)

  if String === body
    response.write stamped(body)
  else
    body.each do |fragment|
      response.write stamped(fragment)
    end
  end
  body.close if body.respond_to? :close
  response.finish
end

#shaObject

Initialiser over class-sha.



39
40
41
# File 'lib/shack/middleware.rb', line 39

def sha
  @sha || self.class.sha
end

#stamped(body) ⇒ Object



43
44
45
# File 'lib/shack/middleware.rb', line 43

def stamped(body)
  Stamp.new(body, sha, self.class.content).result
end