Class: Reins::Model::SQLite
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(data = nil) ⇒ SQLite
Returns a new instance of SQLite.
8
9
10
|
# File 'lib/reins/sqlite_model.rb', line 8
def initialize(data = nil)
@hash = data
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name) ⇒ Object
104
105
106
|
# File 'lib/reins/sqlite_model.rb', line 104
def method_missing(name)
self[name]
end
|
Class Method Details
85
86
87
88
89
90
91
92
93
|
# File 'lib/reins/sqlite_model.rb', line 85
def self.all
rows = DB.execute <<SQL
select #{schema.keys.join ","} from #{table};
SQL
rows.map do |r|
data = Hash[schema.keys.zip r]
self.new data
end
end
|
42
43
44
45
46
|
# File 'lib/reins/sqlite_model.rb', line 42
def self.count
DB.execute(<<SQL)[0][0]
SELECT COUNT(*) FROM #{table}
SQL
end
|
.create(values) ⇒ Object
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
# File 'lib/reins/sqlite_model.rb', line 25
def self.create(values)
values.delete "id"
keys = schema.keys - ["id"]
vals = keys.map do |key|
values[key] ? to_sql(values[key]) : "null"
end
DB.execute <<SQL
INSERT INTO #{table} (#{keys.join ","})
VALUES (#{vals.join ","});
SQL
raw_vals = keys.map { |k| values[k] }
data = Hash[keys.zip raw_vals]
sql = "SELECT last_insert_rowid();"
data["id"] = DB.execute(sql)[0][0]
self.new data
end
|
48
49
50
51
52
53
54
55
|
# File 'lib/reins/sqlite_model.rb', line 48
def self.find(id)
row = DB.execute <<SQL
select #{schema.keys.join ","} from #{table}
where id = #{id};
SQL
data = Hash[schema.keys.zip row[0]]
self.new data
end
|
95
96
97
98
99
100
101
102
|
# File 'lib/reins/sqlite_model.rb', line 95
def self.schema
return @schema if @schema
@schema = {}
DB.table_info(table) do |row|
@schema[row["name"]] = row["type"]
end
@schema
end
|
81
82
83
|
# File 'lib/reins/sqlite_model.rb', line 81
def self.table
Reins.to_underscore name
end
|
.to_sql(val) ⇒ Object
12
13
14
15
16
17
18
19
20
21
22
23
|
# File 'lib/reins/sqlite_model.rb', line 12
def self.to_sql(val)
case val
when NilClass
'null'
when Numeric
val.to_s
when String
"'#{val}'"
else
raise "Can't change #{val.class} to SQL!"
end
end
|
Instance Method Details
57
58
59
|
# File 'lib/reins/sqlite_model.rb', line 57
def [](name)
@hash[name.to_s]
end
|
#[]=(name, value) ⇒ Object
61
62
63
|
# File 'lib/reins/sqlite_model.rb', line 61
def []=(name, value)
@hash[name.to_s] = value
end
|
77
78
79
|
# File 'lib/reins/sqlite_model.rb', line 77
def save
self.save! rescue false
end
|
65
66
67
68
69
70
71
72
73
74
75
|
# File 'lib/reins/sqlite_model.rb', line 65
def save!
fields = @hash.map do |k, v|
"#{k}=#{self.class.to_sql(v)}"
end.join ","
DB.execute <<SQL
UPDATE #{self.class.table}
SET #{fields}
WHERE id = #{@hash["id"]}
SQL
true
end
|