Class: Mashery::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/mashery/query.rb

Constant Summary collapse

OBJECT_TYPES =
['members', 'keys', 'services', 'roles', 'applications']
DEFAULT_QUERIES_PER_SECOND =
2

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object_type, options = {}) ⇒ Query

Returns a new instance of Query.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mashery/query.rb', line 9

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

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



6
7
8
# File 'lib/mashery/query.rb', line 6

def fields
  @fields
end

#object_typeObject (readonly)

Returns the value of attribute object_type.



6
7
8
# File 'lib/mashery/query.rb', line 6

def object_type
  @object_type
end

#pageObject

Returns the value of attribute page.



7
8
9
# File 'lib/mashery/query.rb', line 7

def page
  @page
end

Instance Method Details

#executeObject



38
39
40
# File 'lib/mashery/query.rb', line 38

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

#fetch_all(qps = DEFAULT_QUERIES_PER_SECOND) ⇒ Object

Page through the results. Due heavy use of the API, this method takes a qps parameter to control how often the API is called.



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/mashery/query.rb', line 48

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

#itemsObject



42
43
44
# File 'lib/mashery/query.rb', line 42

def items
  execute['items']
end

#page_clauseObject



26
27
28
# File 'lib/mashery/query.rb', line 26

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

#query_stringObject



34
35
36
# File 'lib/mashery/query.rb', line 34

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

#where_clauseObject



30
31
32
# File 'lib/mashery/query.rb', line 30

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