-
Notifications
You must be signed in to change notification settings - Fork 0
/
sql_object.rb
executable file
·74 lines (62 loc) · 1.47 KB
/
sql_object.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require_relative './associatable'
require_relative './db_connection'
require_relative './mass_object'
require_relative './searchable'
class SQLObject < MassObject
extend Searchable
extend Associatable
def self.set_table_name(table_name)
@table_name = table_name
end
def self.table_name
@table_name
end
def self.all
query = <<-SQL
SELECT *
FROM #{table_name}
SQL
objects = DBConnection.execute(query)
parse_all(objects)
end
def self.find(id)
query = <<-SQL
SELECT *
FROM #{table_name}
WHERE id = ?
SQL
object = DBConnection.execute(query, id).first
new(object)
end
def create
value_escapes = (Array.new(self.class.attributes.count) { "?" }).join(", ")
attribute_names = self.class.attributes.map {|attr| "'#{attr}'"}.join(", ")
query = <<-SQL
INSERT INTO #{self.class.table_name} (#{attribute_names})
VALUES (#{value_escapes})
SQL
DBConnection.execute(query, *attribute_values)
@id = self.class.all.last.id
end
def update
set_attr_string = self.class.attributes.map { |attr| "#{attr} = ?"}.join(", ")
query = <<-SQL
UPDATE #{self.class.table_name}
SET #{set_attr_string}
WHERE id = #{@id}
SQL
DBConnection.execute(query, *attribute_values)
end
def save
if @id
update
else
create
end
end
def attribute_values
self.class.attributes.map do |attr|
send(attr)
end
end
end