Permalink
Browse files

work out middleware context.

  • Loading branch information...
1 parent 585c657 commit 2a0890371fd540072a1cb26a70bc7dc82fd52418 @nearapogee committed Oct 15, 2012
Showing with 32 additions and 12 deletions.
  1. +1 −0 Rakefile
  2. +9 −4 lib/alke/client.rb
  3. +20 −5 lib/alke/middleware_registry.rb
  4. +2 −3 test/test_integration.rb
View
1 Rakefile
@@ -12,6 +12,7 @@ Hoe.spec 'alke' do
dependency('faraday', '~> 0.8.0')
dependency('json', '~> 1.7.5')
+ dependency('isolate', '~> 3.2.2', :dev)
dependency('sinatra', '~> 1.3.3', :dev)
dependency('sinatra-contrib', '~> 1.3.1', :dev)
dependency('sequel', '~> 3.4.0', :dev)
View
13 lib/alke/client.rb
@@ -1,13 +1,17 @@
module Alke
module Client
+
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
module ClassMethods
- def adapter(adapter = nil)
- @adapter ||= adapter || Faraday::Adapter::NetHttp
+ def adapter(adapter = Faraday.default_adapter)
+ if adapter.is_a? Symbol
+ adapter = Faraday::Adapter.lookup_middleware(adapter)
+ end
+ @adapter ||= adapter
end
def host(host = nil)
@@ -114,9 +118,10 @@ def url
end
def save(pass = true, &block)
+ # TODO pass - dup connection
if block_given?
- registry = Alke::MiddlewareRegistry.new(connection)
- registry.update(block)
+ registry = Alke::MiddlewareRegistry.new(self)
+ registry.update(&block)
end
method = persisted? ? :put : :post
response = connection.send(method, url, writable_attributes)
View
25 lib/alke/middleware_registry.rb
@@ -1,13 +1,28 @@
module Alke
class MiddlewareRegistry
- def initialize(connection)
- @connection = connection
+ def initialize(instance)
+ @connection = instance.connection
+ @builder = instance.connection.builder
+ @adapter = instance.class.adapter
end
- def update(block)
- instance_exec(@connection, block)
+ def update(&blk)
+ instance_exec(@connection, &blk)
+ end
+
+ private
+
+ def with(middleware, *args)
+ options = {}
+ options = options.merge(args.pop) if args.last.is_a?(Hash)
+ if options[:before]
+ @builder.insert_before options[:before], middleware, *args
+ elsif options[:after]
+ @builder.insert_after options[:after], middleware, *args
+ else
+ @builder.insert_before @adapter, middleware, *args
+ end
end
-
end
end
View
5 test/test_integration.rb
@@ -17,7 +17,7 @@ class Widget
end
end
- class Md5Signature < Faraday::Middleware
+ class ::Md5Signature < Faraday::Middleware
def call(env)
@app.call(env)
end
@@ -106,15 +106,14 @@ def test_reload_new
end
def test_save_with_middleware
- skip
w = Widget[1]
new_price = w.price * 2
w.price = new_price
w.save do |c|
with Md5Signature
end
assert_equal new_price, w.price
- assert w.connection.builder.handlers.include?(Md5Signature)
+ assert w.connection.builder.handlers.include?(::Md5Signature)
w.reload
assert_equal new_price, w.price
end

0 comments on commit 2a08903

Please sign in to comment.