Module: Architect4r::Model::Queries::ClassMethods

Defined in:
lib/architect4r/model/queries.rb

Instance Method Summary collapse

Instance Method Details

#allObject



55
56
57
# File 'lib/architect4r/model/queries.rb', line 55

def all
  find_by_cypher("start ModelRoot=node(#{self.model_root.id}) match ModelRoot<-[:model_type]-Item return Item", 'Item')
end

#count(opts = {}, &block) ⇒ Object



8
9
10
11
# File 'lib/architect4r/model/queries.rb', line 8

def count(opts = {}, &block)
  data = connection.execute_cypher("start s=node(#{self.model_root.id}) match (s)<-[:model_type]-(d) return count(d)")
  data['data'].flatten.first
end

#find(*ids) ⇒ Object Also known as: find_by_id

Fetch a record of the specified model based on its id



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/architect4r/model/queries.rb', line 15

def find(*ids)
  # This code is taken from / inspired by activerecord:
  #   activerecord/lib/active_record/base.rb, line 1589
  expects_array = ids.first.kind_of?(Array)
  return ids.first if expects_array && ids.first.empty?
  
  ids = ids.flatten.compact.uniq
  
  case ids.size
  when 0
    raise(Architect4r::RecordNotFound.new("Could not find the #{self.name} without an id!"))
  when 1
    id = ids.first.to_i
    data = connection.execute_cypher("start s=node(#{self.model_root.id}), d=node(#{id}) match s<-[r:model_type]-d return d")
    data &&= data['data'] && data['data'].flatten.first
    result = self.build_from_database(data)
    
    expects_array ? [ result ] : result
  else
    ids = ids.map { |i| i.to_i }.uniq.join(',')
    find_by_cypher("start s=node(#{self.model_root.id}), d=node(#{ids}) match s<-[r:model_type]-d return d", 'd')
  end
end

#find!(id) ⇒ Object Also known as: find_by_id!



40
41
42
# File 'lib/architect4r/model/queries.rb', line 40

def find!(id)
  self.find(id) || raise(Architect4r::RecordNotFound.new("Could not find the #{self.name} with id #{id}!"))
end

#find_by_cypher(query, identifier) ⇒ Object

Use this method only to fetch items of the same class.



46
47
48
49
50
51
52
53
# File 'lib/architect4r/model/queries.rb', line 46

def find_by_cypher(query, identifier)
  if result_data = connection.execute_cypher(query)
    result_data = connection.transform_cypher_result_to_hash(result_data)
    result_data.map { |item| connection.convert_if_possible(item[identifier]) }
  else
    nil
  end
end