module GdatastoreMapper::Scoping

Public Instance Methods

all(&block) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 37
def all &block
  order(created_at: :asc, &block)
end
Also aliased as: each
count() click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 50
def count
  all.count
end
each(&block)
Alias for: all
find(id) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 11
def find id
  return nil if id.nil?
  query = Google::Cloud::Datastore::Key.new self.to_s, id.to_i
  entities = GdatastoreMapper::Session.dataset.lookup query
  from_entity entities.first if entities.any?
end
find_by(condition) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 18
def find_by condition
  return nil unless condition.is_a?(Hash)
  where(condition)&.first
end
find_or_create(condition) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 23
def find_or_create condition
  return nil unless condition.is_a?(Hash)
  if record = where(condition)&.first
    record
  else
    create condition
  end
end
first() click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 42
def first
  all.first
end
last() click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 46
def last
  all.last
end
limit(condition) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 54
def limit condition
  return nil unless condition.is_a?(Fixnum)
  all[0..condition-1]
end
order(condition, &block) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 32
def order condition, &block
  return nil unless condition.is_a?(Hash)
  dataset_run(order_query(condition), &block)
end
where(condition, &block) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 6
def where condition, &block
  return nil unless condition.is_a?(Hash)
  dataset_run(where_query(condition), &block)
end

Private Instance Methods

dataset_run(query, &block) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 77
def dataset_run query, &block
  entities = GdatastoreMapper::Session.dataset.run query
  result = GdatastoreMapper::Relation.new(self, nil)
  entities.each do |entity|
    record = from_entity(entity)
    block.call(record) if block_given?
    record = find(record.id)
    result << record if record
  end
  result
end
order_query(condition) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 69
def order_query condition
  query = Google::Cloud::Datastore::Query.new.kind(self.to_s)
  condition.each do |property, value|
    query.order(property.to_s, value)
  end
  query
end
where_query(condition) click to toggle source
# File lib/gdatastore_mapper/scoping.rb, line 61
def where_query condition
  query = Google::Cloud::Datastore::Query.new.kind(self.to_s)
  condition.each do |property, value|
    query.where(property.to_s, '=', value)
  end
  query
end