Sha256: 28ecffdc5c044abbdf209d540d64c06b5d74254f094fd5a3751c2b07d918d118

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

require 'net/http'
require 'uri'
require 'simple_mapper/default_plugins/callbacks'

# SimpleMapper::HttpAdapter.
# Input:
#   get is called with finder options
#   put and post are called with data
#   delete is called with an identifier
# Simply perform the requests, with callbacks, to the appropriate http host.
module SimpleMapper
  class HttpAdapter
    include Callbacks

    attr_accessor :base_url
    alias :set_base_url :base_url=
    def base_uri
      URI.parse(base_url)
    end

    def headers
      @headers ||= {}
    end
    def headers=(v)
      raise TypeError, "headers set must be a hash" unless v.is_a?(Hash)
      headers.merge!(v)
    end
    alias :set_headers :headers=

    def get(*args)
      http.request(request('get', base_uri.path)).body
    end

    def put(identifier,data)
      http.request(request('put', URI.parse(identifier).path, data)).body
    end

    def post(data)
      http.request(request('post', base_uri.path, data)).body
    end

    # In the http adapter, the identifier is a url.
    def delete(identifier)
      http.request(request('delete', URI.parse(identifier).path)).body
    end

    private
      def http(refresh=false)
        @http = Net::HTTP.new(base_uri.host, base_uri.port) if @http.nil? || refresh
        @http
      end

      def request(verb,path,body=nil,options={})
        request_class = Net::HTTP.const_get verb.to_s.capitalize
        request = request_class.new path
        request.body = body
        request.initialize_http_header headers.merge(options[:headers] || {})
        # - - - after_request_instantiate callback
        request = run_callback('initialize_request', request)
        # - - -
        request
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
simplemapper-0.0.1 lib/simple_mapper/adapters/http_adapter.rb