Module: Gamifier::Model::FinderMethods

Included in:
Collection
Defined in:
lib/gamifier/model.rb

Overview

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.

Instance Method Summary collapse

Instance Method Details

#all(params = {}, &block) ⇒ Object

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.



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
# 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 = {}) ⇒ Object



134
135
136
137
# 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 = {}) ⇒ Object



119
120
121
122
123
124
# 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 = {}) ⇒ Object



130
131
132
# File 'lib/gamifier/model.rb', line 130

def find_by_label(label, params = {})
  find_by(:label, label, params)
end

#find_by_name(name, params = {}) ⇒ Object



126
127
128
# File 'lib/gamifier/model.rb', line 126

def find_by_name(name, params = {})
  find_by(:name, name, params)
end

#find_or_create(key, params = {}) ⇒ Object



139
140
141
# File 'lib/gamifier/model.rb', line 139

def find_or_create(key, params = {})
  find(key, params) || build(params).save
end