module Gamifier::Model::FinderMethods

To be included as instance methods into the Collection class used to instantiate and find objects. Add more in descendants if you want to add more methods. See Gamifier::Player for an example.

Public Instance Methods

all(params = {}) { |entry| ... } click to toggle source

Fetch all the records according to the given query parameters. If a block is given, it will automatically lazy-load all the pages and yield each entry, until all the items have been loaded, or until the user returns from the block.

# File lib/gamifier/model.rb, line 101
def all(params = {}, &block)
  params[:page] ||= 1
  params[:per_page] ||= 50
  res = engine.transmit(:get, path, :query => params)
  if res.kind_of?(Hash)
    entries = map_to_models(res)
    if block
      # Lazy load all the pages
      entries.each{|entry| yield(entry)}
      params[:page] += 1
      all(params, &block) unless res['paging'].empty? || res['data'].empty?
    end
    entries
  else
    res
  end
end
find(key, params = {}) click to toggle source
# File lib/gamifier/model.rb, line 134
def find(key, params = {})
  res = engine.transmit(:get, [path, key].join("/"), :query => params)
  select_first_entry_if_any(res)
end
find_by(key, value, params = {}) click to toggle source
# File lib/gamifier/model.rb, line 119
def find_by(key, value, params = {})
  all(params) do |entry|
    return entry if entry.respond_to?(key) && entry.send(key) == value.to_s
  end
  return nil
end
find_by_label(label, params = {}) click to toggle source
# File lib/gamifier/model.rb, line 130
def find_by_label(label, params = {})
  find_by(:label, label, params)
end
find_by_name(name, params = {}) click to toggle source
# File lib/gamifier/model.rb, line 126
def find_by_name(name, params = {})
  find_by(:name, name, params)
end
find_or_create(key, params = {}) click to toggle source
# File lib/gamifier/model.rb, line 139
def find_or_create(key, params = {})
  find(key, params) || build(params).save
end

Protected Instance Methods

map_to_models(response) click to toggle source
# File lib/gamifier/model.rb, line 156
def map_to_models(response)
  response['data'].map{|h| build(h)}
end
select_first_entry_if_any(response) click to toggle source

Selects the first entry out of a data array, or out of a single data entry.

# File lib/gamifier/model.rb, line 146
def select_first_entry_if_any(response)
  if response.kind_of?(Hash) && response.has_key?('data')
    entry = [response['data']].flatten[0]
    return nil if entry.nil?
    build(entry)
  else
    response
  end
end