Class: EasyMvc::Mapper
Constant Summary
collapse
- @@db =
SQLite3::Database.new File.join "db", "app.db"
- @@table_name =
""
- @@model =
nil
- @@mapping =
{ }
Class Method Summary
collapse
Instance Method Summary
collapse
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args) ⇒ Object
52
53
54
|
# File 'lib/easymvc/mapper.rb', line 52
def method_missing(method, *args)
@model.send method
end
|
Class Method Details
56
57
58
59
|
# File 'lib/easymvc/mapper.rb', line 56
def self.find(id)
row = @@db.execute("SELECT #{@@mapping.keys.join(",")} FROM #{@@table_name} WHERE id=?", id).first
self.map_row_to_object(row)
end
|
70
71
72
73
74
75
|
# File 'lib/easymvc/mapper.rb', line 70
def self.find_all
data = @@db.execute "SELECT #{@@mapping.keys.join(",")} FROM #{@@table_name}"
data.map do |row|
self.map_row_to_object(row)
end
end
|
.map_row_to_object(row) ⇒ Object
61
62
63
64
65
66
67
68
|
# File 'lib/easymvc/mapper.rb', line 61
def self.map_row_to_object(row)
model = @@model.new
@@mapping.each_value.with_index do |attribute, index|
model.send "#{attribute}=", row[index]
end
model
end
|
Instance Method Details
#delete(id) ⇒ Object
77
78
79
|
# File 'lib/easymvc/mapper.rb', line 77
def delete(id)
@@db.execute "DELETE FROM #{@@table_name} WHERE id=?", id
end
|
#get_columns ⇒ Object
38
39
40
41
42
|
# File 'lib/easymvc/mapper.rb', line 38
def get_columns
column = @@mapping.keys
column.delete(:id)
column.join(",")
end
|
#get_values ⇒ Object
32
33
34
35
36
|
# File 'lib/easymvc/mapper.rb', line 32
def get_values
attributes = @@mapping.values
attributes.delete(:id)
attributes.map { |method| self.send(method) }
end
|
#new_record_placeholders ⇒ Object
22
23
24
|
# File 'lib/easymvc/mapper.rb', line 22
def new_record_placeholders
(["?"] * (@@mapping.size - 1)).join(",")
end
|
#new_record_values ⇒ Object
48
49
50
|
# File 'lib/easymvc/mapper.rb', line 48
def new_record_values
get_values
end
|
#save(model) ⇒ Object
10
11
12
13
14
15
16
17
18
19
20
|
# File 'lib/easymvc/mapper.rb', line 10
def save(model)
@model = model
if model.id
@@db.execute %Q(
UPDATE #{@@table_name}
SET #{update_record_placeholders}
where id = ?), update_record_values
else
@@db.execute "INSERT INTO #{@@table_name} (#{get_columns}) VALUES (#{new_record_placeholders})", new_record_values
end
end
|
#update_record_placeholders ⇒ Object
26
27
28
29
30
|
# File 'lib/easymvc/mapper.rb', line 26
def update_record_placeholders
column = @@mapping.keys
column.delete(:id)
column.map { |col| "#{col}=?" }.join(",")
end
|
#update_record_values ⇒ Object
44
45
46
|
# File 'lib/easymvc/mapper.rb', line 44
def update_record_values
get_values << self.send(:id)
end
|