lib/ahora/resource.rb in ahora-0.0.2 vs lib/ahora/resource.rb in ahora-0.0.3

- old
+ new

@@ -2,48 +2,56 @@ module Ahora module Resource attr_writer :document_parser - def get(url, params = {}) - connection.get do |req| - set_common_headers(req) - req.url url, params + def get(url, params = nil) + connection.run_request(:get, url, nil, nil) do |req| + req.params.update(params) if params + yield req if block_given? end end # FIXME test - def post(url, body) - connection.post do |req| - set_common_headers(req) - req.url url - req.body = body + def post(url, body = nil) + connection.run_request(:post, url, body, nil) do |req| + yield req if block_given? end end # FIXME test - def put(url, body) - connection.put do |req| - set_common_headers(req) - req.url url - req.body = body + def put(url, body = nil) + connection.run_request(:put, url, body, nil) do |req| + yield req if block_given? end end def connection - conn = Faraday.new(host, :ssl => { :verify => false }) do |builder| - builder.use Faraday::Response::RaiseError - extend_middleware(builder) - builder.adapter Faraday.default_adapter + Faraday.new(host.dup, connection_options) do |conn| + conn.use Faraday::Response::RaiseError + extend_middleware(conn.builder) + unless conn.builder.handlers.any? {|mid| mid.klass < Faraday::Adapter } + conn.adapter Faraday.default_adapter + end end - conn.headers['User-Agent'] = 'Ahora' - conn end # @abstract override to use custom Faraday middleware - def extend_middleware(builder); end; + def extend_middleware(builder) + super if defined? super + end + # FIXME test (FakeWeb cannot test request headers) + # @abstract override to set custome headers + # returns a hash with a string for each key + def headers + (defined?(super) ? super.dup : {}).update \ + :user_agent => 'Ahora', + :content_type => 'application/xml', + :accept => 'application/xml' + end + def collection(*args, &block) if args.size == 2 klass, response = args instantiator = lambda do |doc| klass.parse(doc) @@ -58,11 +66,11 @@ private def document_parser @document_parser ||= XmlParser.method(:parse) end - def set_common_headers(req) - req.headers['Content-Type'] = 'application/xml' - req.headers['Accept'] = 'application/xml' + def connection_options + (defined?(super) ? super.dup : {}).update \ + :headers => headers end end -end \ No newline at end of file +end