Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
razorsync / lib / razorsync / request.rb
Size: Mime:
module Razorsync
  # Defines HTTP request methods
  module Request
    # Perform an HTTP GET request
    def get(path, options = {})
      request(:get, path, options)
    end

    # Perform an HTTP POST request
    def post(path, options = {})
      request(:post, path, options)
    end

    private

    # Perform an HTTP request
    def request(method, path, options)
      begin
        response = connection.send(method) do |request|
          case method
          when :get
            formatted_options = format_options(options)
            request.url(path,formatted_options)
          when :post, :put
            request.headers['Content-Type'] = 'application/json'
            request.body = options.to_json unless options.empty?
            request.url(path)
          end
          request.options.timeout = 30        # read timeout
          request.options.open_timeout = 60   # connection timeout
        end
      rescue Faraday::ConnectionFailed => e
        raise ConnectionError.new(e)
      rescue Faraday::TimeoutError => e
        raise TimeoutError.new(e)
      rescue Faraday::ResourceNotFound => e
        raise NotFoundError.new(e)
      rescue Faraday::ParsingError => e
        raise ParseError.new(e)
      rescue Faraday::SSLError => e
        raise SSLError.new(e)
      rescue => e
        raise Error.new(e)
      end

      Response.create(response.body)
    end

    # TODO: Replace these options with whatever options you need to pass for the target API.
    # Format the Options before you send them off to Razorsync
    def format_options(options)
      return if options.blank?
      options[:fields]     = format_fields(options[:fields]) if options.has_key?(:fields)
      options[:limit]      = options[:limit] if options.has_key?(:limit)
      options[:pageindex]  = options[:page]  if options.has_key?(:page)
      options[:q]          = options[:q]  if options.has_key?(:q)
      options[:wField]     = options[:wField] if options.has_key?(:wField)
      options[:wOperator]  = options[:wOperator] if options.has_key?(:wOperator)
      options[:wValue]     = options[:wValue] if options.has_key?(:wValue)

      return options
    end

    # TODO: Replace or remove this method if necessary.
    # Format the fields to a format that the Razorsync likes
    # @param [Array or String] fields can be specified as an Array or String
    # @return String
    def format_fields(fields)
      if fields.instance_of?(Array)
        return fields.join(",")
      elsif fields.instance_of?(String)
        return fields
      end
    end

  end
end