Class: Rack::Berater

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/berater.rb,
lib/rack/berater/railtie.rb,
lib/rack/berater/version.rb,
lib/rack/berater/prioritizer.rb,
lib/rack/berater/rails_prioritizer.rb

Defined Under Namespace

Classes: Prioritizer, RailsPrioritizer, Railtie

Constant Summary collapse

ERRORS =
Set[ ::Berater::Overloaded ]
VERSION =
"0.4.1"

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Berater.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rack/berater.rb', line 14

def initialize(app, options = {})
  @app = app
  @enabled = options[:enabled?]
  @limiter = options[:limiter]
  @options = {
    headers: {},
    status_code: options.fetch(:status_code, 429),
  }

  # configure body
  @options[:body] = case options[:body]
    when true, nil
      Rack::Utils::HTTP_STATUS_CODES[@options[:status_code]]
    when false
      nil
    when String
      options[:body]
    else
      raise ArgumentError, 'invalid :body option: #{options[:body]}'
    end

  # configure headers
  if @options[:body]
    @options[:headers][Rack::CONTENT_TYPE] = 'text/plain'
  end
  @options[:headers].update(options.fetch(:headers, {}))
end

Instance Method Details

#call(env) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rack/berater.rb', line 42

def call(env)
  if enabled?(env)
    limit(env) { @app.call(env) }
  else
    @app.call(env)
  end
rescue *ERRORS => e
  [
    @options[:status_code],
    @options[:headers],
    [ @options[:body] ].compact,
  ]
end