Module: BazaModels::Model::Queries::ClassMethods

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

Instance Method Summary collapse

Instance Method Details

#find(id) ⇒ Object



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

def find(id)
  row = db.select(table_name, {id: id}, limit: 1).fetch
  raise BazaModels::Errors::RecordNotFound, "Record not found by ID: #{id}" unless row
  new(row, init: true)
end

#find_by(where_hash) ⇒ Object



13
14
15
16
17
# File 'lib/baza_models/model/queries.rb', line 13

def find_by(where_hash)
  row = db.select(table_name, where_hash, limit: 1).fetch
  return new(row, init: true) if row
  false
end

#find_by!(where_hash) ⇒ Object



19
20
21
22
23
# File 'lib/baza_models/model/queries.rb', line 19

def find_by!(where_hash)
  model = find_by(where_hash)
  return model if model
  raise BazaModels::Errors::RecordNotFound, "Record not found by arguments: #{where_hash}" unless model
end

#find_or_create_by(data) {|model| ... } ⇒ Object

Yields:

  • (model)


31
32
33
34
35
36
# File 'lib/baza_models/model/queries.rb', line 31

def find_or_create_by(data)
  model = find_or_initialize_by(data)
  model.save if model.new_record?
  yield model if block_given?
  model
end

#find_or_create_by!(data) {|model| ... } ⇒ Object

Yields:

  • (model)


38
39
40
41
42
43
# File 'lib/baza_models/model/queries.rb', line 38

def find_or_create_by!(data)
  model = find_or_initialize_by(data)
  model.save! if model.new_record?
  yield model if block_given?
  model
end

#find_or_initialize_by(data) ⇒ Object



25
26
27
28
29
# File 'lib/baza_models/model/queries.rb', line 25

def find_or_initialize_by(data)
  model = find_by(data)
  return model if model
  new(data)
end