Class: Faraday::Middleware

Inherits:
Object
  • Object
show all
Extended by:
MiddlewareRegistry
Defined in:
lib/faraday/middleware.rb

Overview

Middleware is the basic base class of any Faraday middleware.

Constant Summary collapse

DEFAULT_OPTIONS =
{}.freeze
LOCK =
Mutex.new

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from MiddlewareRegistry

lookup_middleware, register_middleware, registered_middleware, unregister_middleware

Constructor Details

#initialize(app = nil, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



15
16
17
18
# File 'lib/faraday/middleware.rb', line 15

def initialize(app = nil, options = {})
  @app = app
  @options = self.class.default_options.merge(options)
end

Instance Attribute Details

#appObject (readonly)

Returns the value of attribute app.



10
11
12
# File 'lib/faraday/middleware.rb', line 10

def app
  @app
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/faraday/middleware.rb', line 10

def options
  @options
end

Class Method Details

.default_optionsObject

default_options attr_reader that initializes class instance variable with the values of any Faraday::Middleware defaults, and merges with subclass defaults



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

def default_options
  @default_options ||= DEFAULT_OPTIONS.merge(self::DEFAULT_OPTIONS)
end

.default_options=(options = {}) ⇒ Object

Faraday::Middleware::default_options= allows user to set default options at the Faraday::Middleware class level.

my_app/config/initializers/my_faraday_middleware.rb

Faraday::Response::RaiseError.default_options = { include_request: false }

Examples:

Set the Faraday::Response::RaiseError option, include_request to false



29
30
31
32
33
34
# File 'lib/faraday/middleware.rb', line 29

def default_options=(options = {})
  validate_default_options(options)
  LOCK.synchronize do
    @default_options = default_options.merge(options)
  end
end

Instance Method Details

#call(env) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/faraday/middleware.rb', line 54

def call(env)
  on_request(env) if respond_to?(:on_request)
  app.call(env).on_complete do |environment|
    on_complete(environment) if respond_to?(:on_complete)
  end
rescue StandardError => e
  on_error(e) if respond_to?(:on_error)
  raise
end

#closeObject



64
65
66
67
68
69
70
# File 'lib/faraday/middleware.rb', line 64

def close
  if app.respond_to?(:close)
    app.close
  else
    warn "#{app} does not implement \#close!"
  end
end