Module: Jetski::Model::CrudHelpers::ClassMethods

Defined in:
lib/jetski/model/crud_helpers.rb

Instance Method Summary collapse

Instance Method Details

#allObject



54
55
56
57
58
59
60
61
# File 'lib/jetski/model/crud_helpers.rb', line 54

def all
  columns, *rows = db.execute2( "select * from #{pluralized_table_name}" )
  _all = []
  rows.map do |row|
    _all << format_model_obj(row, columns)
  end
  _all
end

#create(hash_args = nil, **key_args) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/jetski/model/crud_helpers.rb', line 18

def create(hash_args = nil, **key_args)
  args = if hash_args && hash_args.is_a?(Hash)
    hash_args
  else
    key_args
  end

  return puts "#{table_name.capitalize}.create was called with no args" if args.size == 0
  data_values = args.map { |k,v| v }
  key_names = args.map { |k, v| k }
  
  # Set default values on create

  key_names.append "created_at"
  data_values.append Time.now.to_s

  current_record_count = (count || 0)
  record_id = current_record_count + 1
  key_names.append "id"
  data_values.append(record_id)

  sql_command = <<~SQL
    INSERT INTO #{pluralized_table_name} (#{key_names.join(", ")}) 
    VALUES (#{(1..key_names.size).map { |n| "?" }.join(", ")})
  SQL

  db.execute(sql_command, data_values)

  record_attributes = {}
  key_names.each.with_index do |k, i|
    record_attributes[k.to_sym] = data_values[i]
  end

  new(**record_attributes)
end

#destroy_all!Object



70
71
72
# File 'lib/jetski/model/crud_helpers.rb', line 70

def destroy_all! 
  db.execute("DELETE from #{pluralized_table_name}")
end

#find(id) ⇒ Object



63
64
65
66
67
# File 'lib/jetski/model/crud_helpers.rb', line 63

def find(id)
  id_as_integer = id.to_i
  columns, *rows = db.execute2( "select * from #{pluralized_table_name} WHERE id=?", id_as_integer)
  format_model_obj(rows.last, columns)
end