Module: Faraday::MiddlewareRegistry
- Included in:
- Middleware, Request, Response
- Defined in:
- lib/faraday.rb
Overview
Public: Adds the ability for other modules to register and lookup middleware classes.
Instance Method Summary collapse
- #fetch_middleware(key) ⇒ Object
- #load_middleware(key) ⇒ Object
-
#lookup_middleware(key) ⇒ Object
Public: Lookup middleware class with a registered Symbol shortcut.
- #middleware_mutex(&block) ⇒ Object
-
#register_middleware(autoload_path = nil, mapping = nil) ⇒ Object
Public: Register middleware class(es) on the current module.
Instance Method Details
#fetch_middleware(key) ⇒ Object
200 201 202 |
# File 'lib/faraday.rb', line 200 def fetch_middleware(key) defined?(@registered_middleware) && @registered_middleware[key] end |
#load_middleware(key) ⇒ Object
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 |
# File 'lib/faraday.rb', line 204 def load_middleware(key) value = fetch_middleware(key) case value when Module value when Symbol, String middleware_mutex do @registered_middleware[key] = const_get(value) end when Proc middleware_mutex do @registered_middleware[key] = value.call end when Array middleware_mutex do const, path = value if root = @middleware_autoload_path path = "#{root}/#{path}" end require(path) @registered_middleware[key] = const end load_middleware(key) end end |
#lookup_middleware(key) ⇒ Object
187 188 189 190 |
# File 'lib/faraday.rb', line 187 def lookup_middleware(key) load_middleware(key) || raise(Faraday::Error.new("#{key.inspect} is not registered on #{self}")) end |
#middleware_mutex(&block) ⇒ Object
192 193 194 195 196 197 198 |
# File 'lib/faraday.rb', line 192 def middleware_mutex(&block) @middleware_mutex ||= begin require 'monitor' Monitor.new end @middleware_mutex.synchronize(&block) end |
#register_middleware(autoload_path = nil, mapping = nil) ⇒ Object
Public: Register middleware class(es) on the current module.
mapping - A Hash mapping Symbol keys to classes. Classes can be expressed
as fully qualified constant, or a Proc that will be lazily
called to return the former.
Examples
module Faraday
class Whatever
# Middleware looked up by :foo returns Faraday::Whatever::Foo.
register_middleware :foo => Foo
# Middleware looked up by :bar returns Faraday::Whatever.const_get(:Bar)
register_middleware :bar => :Bar
# Middleware looked up by :baz requires 'baz' and returns Faraday::Whatever.const_get(:Baz)
register_middleware :baz => [:Baz, 'baz']
end
end
Returns nothing.
160 161 162 163 164 165 166 167 168 169 |
# File 'lib/faraday.rb', line 160 def register_middleware(autoload_path = nil, mapping = nil) if mapping.nil? mapping = autoload_path autoload_path = nil end middleware_mutex do @middleware_autoload_path = autoload_path if autoload_path (@registered_middleware ||= {}).update(mapping) end end |