Class: Wings::Model::SQLite
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(data = nil) ⇒ SQLite
Returns a new instance of SQLite.
66
67
68
|
# File 'lib/wings/sqlite_model.rb', line 66
def initialize(data = nil)
@data = data
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
102
103
104
105
106
107
108
109
110
111
|
# File 'lib/wings/sqlite_model.rb', line 102
def method_missing(name, *args)
unless self.class.schema.keys.include?(name.to_s)
return super
end
self.class.define_method(name.to_sym) do
@data[name.to_s]
end
@data[name.to_s]
end
|
Class Method Details
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/wings/sqlite_model.rb', line 38
def self.all
all_rows = db.execute " SELECT * FROM \#{table};\n"
all_rows.map do |row|
data = Hash[schema.keys.zip(row)]
self.new(data)
end
end
|
49
50
51
52
53
54
|
# File 'lib/wings/sqlite_model.rb', line 49
def self.count
sql = " SELECT COUNT(*) FROM \#{table};\n"
db.execute(sql)[0][0]
end
|
.create(values) ⇒ Object
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# File 'lib/wings/sqlite_model.rb', line 8
def self.create(values)
keys_without_id = schema.keys - ['id']
db_attributes = keys_without_id.reduce({}) do |memo, key|
memo[key] = values[key] ? to_sql(values[key]) : 'null'
memo
end
db.execute " INSERT INTO \#{table} (\#{db_attributes.keys.join(',')})\n VALUES (\#{db_attributes.values.join(',')});\n"
data = keys_without_id.reduce({}) do |memo, key|
memo[key] = values[key]
memo
end
data['id'] = db.execute('SELECT last_insert_rowid();')[0][0]
self.new(data)
end
|
29
30
31
32
33
34
35
36
|
# File 'lib/wings/sqlite_model.rb', line 29
def self.find(id)
target = db.execute " SELECT * FROM \#{table} WHERE id = \#{id};\n"
data = Hash[schema.keys.zip(target[0])]
self.new(data)
end
|
56
57
58
59
60
61
62
63
64
|
# File 'lib/wings/sqlite_model.rb', line 56
def self.schema
return @schema if @schema
@schema = {}
db.table_info(table) do |row|
@schema[row['name']] = row['type']
end
@schema
end
|
Instance Method Details
70
71
72
|
# File 'lib/wings/sqlite_model.rb', line 70
def [](name)
@data[name.to_s]
end
|
#[]=(name, value) ⇒ Object
74
75
76
|
# File 'lib/wings/sqlite_model.rb', line 74
def []=(name, value)
@data[name.to_s] = value
end
|
97
98
99
|
# File 'lib/wings/sqlite_model.rb', line 97
def save
self.save! rescue false
end
|
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
# File 'lib/wings/sqlite_model.rb', line 78
def save!
unless @data['id']
self.class.create(@data)
return true
end
fields = @data.map do |key, value|
"#{key}=#{self.class.to_sql(value)}"
end.join(',')
self.class.db.execute " UPDATE \#{self.class.table}\n SET \#{fields}\n WHERE id = \#{@data['id']};\n"
true
end
|