Sha256: c57684e802fedbcd069c2ec92a47bff2cbcd7fd3c5674b8a0165a3a5a6b476a2

Contents?: true

Size: 1.57 KB

Versions: 2

Compression:

Stored size: 1.57 KB

Contents

#
# This class handles this aspect of the API:
#
# http://support.mashery.com/docs/read/mashery_api/20/Query_Language
#
module Masheri
  class Query
    OBJECT_TYPES = ['members', 'keys', 'services', 'roles', 'applications']
    DEFAULT_QUERIES_PER_SECOND = 2

    attr_reader :object_type, :fields
    attr_accessor :page

    def initialize(object_type, options={})
      if !OBJECT_TYPES.include?(object_type)
        raise "Invalid object type. '#{object_type}' must be in #{OBJECT_TYPES.inspect}"
      end

      @object_type = object_type

      if options[:fields]
        @fields = options[:fields]
      else
        @fields = "*"
      end

      @where = options[:where]
      @page = options[:page]
    end

    def page_clause
      "PAGE #{@page}" if @page
    end

    def where_clause
      "WHERE #{@where}" if @where
    end

    def query_string
      "SELECT #{fields} FROM #{object_type} #{where_clause} #{page_clause}"
    end

    def execute
      Masheri.client.call_remote('object.query', query_string)
    end

    def items
      execute['items']
    end

    # Page through the results. Due heavy use of the API, this method
    # takes a qps parameter to control how often the API is called.
    def fetch_all(qps = DEFAULT_QUERIES_PER_SECOND)
      response = execute
      items = response['items']

      while response['current_page'] < response['total_pages']
        self.page = response['current_page'] + 1
        response = execute
        items = items + response['items']

        sleep(1.0/DEFAULT_QUERIES_PER_SECOND)
      end

      return items
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
masheri-0.3.5 lib/masheri/query.rb
masheri-0.3.4 lib/masheri/query.rb