Sha256: 2f8cc8b40d1b1d9c56e32cd0b124568f4744660d731653732a0df29f7e8ebf22

Contents?: true

Size: 1.67 KB

Versions: 6

Compression:

Stored size: 1.67 KB

Contents

module MambaNation
  class Request
    extend Forwardable
    
    def self.get(client, path, options={})
      new(client, :get, path, options).perform
    end
    
    def self.post(client, path, options={})
      new(client, :post, path, options).perform
    end
    
    def self.put(client, path, options={})
      options[:body] ||= ""
      new(client, :put, path, options).perform
    end
    
    def self.delete(client, path, options={})
      new(client, :delete, path, options).perform
    end
    
    attr_reader :client, :method, :path, :options
    
    def_delegators :client, :get, :post, :put, :delete
    
    def initialize(client, method, path, options={})
      @client, @method, @path, @options = client, method, path, options
    end
    
    def uri
      @uri ||= begin
        uri = URI.parse(path)
        
        if options[:query] && options[:query] != {}
          uri.query = to_query(options[:query])
        end
        
        uri.to_s
      end
    end
    
    def perform
      MambaNation.make_friendly(send("perform_#{method}"))
    end
    
    private
    
    def perform_get
      get(uri, options[:headers])
    end
    
    def perform_post
      post(uri, options[:body], options[:headers])
    end
    
    def perform_put
      put(uri, options[:body], options[:headers])
    end
    
    def perform_delete
      delete(uri, options[:headers])
    end
    
    def to_query(options)
      options.inject([]) do |collection, opt|
        collection << case opt[1].class.to_s
          when "Array" then opt[1].map { |value| "#{opt[0]}[]=#{value}" }.join('&')
          else "#{opt[0]}=#{opt[1]}"
        end
        collection
      end * '&'
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
mambanation-0.2.2 lib/mambanation/request.rb
mambanation-0.2.1 lib/mambanation/request.rb
mambanation-0.1.32 lib/mambanation/request.rb
mambanation-0.1.31 lib/mambanation/request.rb
mambanation-0.1.29 lib/mambanation.rb
mambanation-0.1.28 lib/mambanation.rb