Permalink
Browse files

add some autoloading abilities to MiddlewareRegistry

  • Loading branch information...
1 parent a6c6f16 commit 497caa3c5ec0a43a2d138b6d14b8d7f2b1f3cbf7 @technoweenie committed Oct 20, 2012
Showing with 42 additions and 5 deletions.
  1. +29 −5 lib/faraday.rb
  2. +11 −0 test/middleware_stack_test.rb
  3. +2 −0 test/strawberry.rb
View
@@ -133,11 +133,22 @@ module MiddlewareRegistry
# 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.
- def register_middleware(mapping)
+ def register_middleware(autoload_path = nil, mapping = nil)
+ if mapping.nil?
+ mapping = autoload_path
+ autoload_path = nil
+ end
+ @middleware_autoload_path = autoload_path if autoload_path
(@registered_middleware ||= {}).update(mapping)
end
@@ -158,11 +169,24 @@ def register_middleware(mapping)
#
# Returns a middleware Class.
def lookup_middleware(key)
- unless defined? @registered_middleware and found = @registered_middleware[key]
- raise "#{key.inspect} is not registered on #{self}"
+ value = defined?(@registered_middleware) && @registered_middleware[key]
+ case value
+ when Module then value
+ when Symbol, String
+ @registered_middleware[key] = const_get(value)
+ when Proc
+ @registered_middleware[key] = value.call
+ when Array
+ const, path = value
+ if root = @middleware_autoload_path
+ path = "#{root}/#{path}"
+ end
+ require(path)
+ @registered_middleware[key] = const
+ lookup_middleware(key)
+ else
+ raise Faraday::Error.new("#{key.inspect} is not registered on #{self}")
end
- found = @registered_middleware[key] = found.call if found.is_a? Proc
- found.is_a?(Module) ? found : const_get(found)
end
end
@@ -123,6 +123,17 @@ def test_registered_symbol_with_proc
end
end
+ def test_registered_symbol_with_array
+ Faraday::Middleware.register_middleware File.expand_path("..", __FILE__),
+ :strawberry => [lambda { Strawberry }, 'strawberry']
+ begin
+ build_stack :strawberry
+ assert_handlers %w[Strawberry]
+ ensure
+ unregister_middleware Faraday::Middleware, :strawberry
+ end
+ end
+
def test_missing_dependencies
build_stack Broken
err = assert_raises RuntimeError do
View
@@ -0,0 +1,2 @@
+class MiddlewareStackTest::Strawberry < MiddlewareStackTest::Handler
+end

0 comments on commit 497caa3

Please sign in to comment.