Sha256: af74c0df05d3295f2a3bf49dc227456bf8f900832052010ee88975356d07e512

Contents?: true

Size: 1.45 KB

Versions: 2

Compression:

Stored size: 1.45 KB

Contents

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.1 lib/masheri/query.rb
masheri-0.2.0 lib/masheri/query.rb