Sha256: 30d68b9de9b394328bfb246209a2b7662a32208f7229f53708d582a79dcec239

Contents?: true

Size: 1.83 KB

Versions: 1

Compression:

Stored size: 1.83 KB

Contents

require "httparty"

module OneEye
  class API
    include HTTParty
    base_uri "https://stg-api.edmodoqabranch.com"

    def self.http_methods
      [:get, :post, :put, :patch, :delete]
    end

    def initialize(api_token=ENV["ONE_EYE_API_KEY"])
      @options = { query: {api_token: api_token} }
    end

    def self.debug(options={})
      OneEye::API.debug_output $stdout unless options[:stop]
      OneEye::API.debug_output $stderr if     options[:stop]
    end

    def handle_errors(&block)
      @response   = block.call
      @code_level = @response.code.to_s[0]

      if @code_level == "4" || @code_level == "5"
        def @response.to_hash
          {:status_code => @response.code, :error => @response.message}
        end
      end

      @response
    end

    http_methods.each do |method_name|
      define_method method_name do |name, options|
        name, options = standardize_request(method_name, name, options)
        handle_errors { self.class.send method_name, name, options }
      end
    end

  private
    def method_missing(name, options={})
      name, options = standardize_request(:get, name, options)
      self.class.get name, options
    end

    def standardize_request(http_method, name, options)
      name    = "/#{name}"
      # name  = slash_name(name)
      options = standardize_options(options)
      name += "/#{options[:id]}" if options.keys.include? :id
      [name, options]
    end

    def slash_name(name)
      "/#{name.to_s.gsub(/\_/) { "/" }}"
    end

    def standardize_options(options={})
      if options.class == Fixnum
        options = {id: options}
      end
      options.each { |k, v| @options[k] ||= v }
      @options[:query]   = @options[:query].merge(options)
      @options[:body]    = options.to_json
      @options[:headers] = {"Content-Type"=>"application/json"}
      @options
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
one-eye-eater-0.1.15 lib/api.rb