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

.configuration=(value) ⇒ Object (writeonly)

Sets the attribute configuration

Parameters:

  • value

    the value to set the attribute configuration to.



54
55
56
# File 'lib/shack/middleware.rb', line 54

def configuration=(value)
  @configuration = value
end

Class Method Details

.configObject



56
57
58
# File 'lib/shack/middleware.rb', line 56

def config
  @configuration ||= Configuration.new
end

.configure(&block) ⇒ Object

Allow configuration of the Middleware

Shack::Middleware.configure do |shack|
  shack.sha = "thisiasha"
  shack.hide_stamp = true
end


67
68
69
# File 'lib/shack/middleware.rb', line 67

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

Instance Method Details

#call(env) ⇒ Object



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

def call(env)
  # Make it easy to get sha from other processes
  Shack.sha = sha
  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

#configObject



24
25
26
# File 'lib/shack/middleware.rb', line 24

def config
  self.class.config
end

#inject_stamp(status, headers, body) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/shack/middleware.rb', line 28

def inject_stamp(status, headers, body)
  return nil if !!config.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 config-sha.



45
46
47
# File 'lib/shack/middleware.rb', line 45

def sha
  @sha || config.sha
end

#stamped(body) ⇒ Object



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

def stamped(body)
  Stamp.new(body, sha, config).result
end