-
Notifications
You must be signed in to change notification settings - Fork 67
/
model.gb
99 lines (81 loc) · 2.22 KB
/
model.gb
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
require "db"
# Some PG settings
db_user = ENV["POSTGRES_USER"] || "postgres"
db_name = ENV["POSTGRES_DB"] || "goby_test"
db_host = ENV["POSTGRES_HOST"] || "0.0.0.0"
pg_host = ENV["DATABASE_URL"]
if pg_host.nil?
pg_host = String.fmt("user=%s dbname=%s host=%s sslmode=disable", db_user, db_name, db_host)
end
PG = DB.open("postgres", pg_host)
PG.run("create table if not exists list_items (
id serial primary key,
title varchar(40),
checked boolean
)")
class ListItem
attr_reader :id, :title, :checked, :error
def initialize(params)
@id ||= params[:id]
@title ||= params[:title]
@checked ||= params[:checked]
@error ||= params[:error]
end
def check
db.exec('UPDATE list_items SET checked = true WHERE id = $1', @id)
@checked = true
end
def uncheck
db.exec('UPDATE list_items SET checked = false WHERE id = $1', @id)
@checked = false
end
def update_title(title)
db.exec('UPDATE list_items SET title = $1 WHERE id = $2', title, @id)
end
def destroy
db.exec('DELETE FROM list_items WHERE id = $1', @id)
end
def valid?
@error.nil?
end
def db
self.class.db
end
def self.db
PG
end
def self.all
db.query("SELECT * FROM list_items ORDER BY id DESC")
end
def self.find(id)
result = db.query("SELECT * FROM list_items WHERE id = $1", id).first
if result
new({ id: result[:id], title: result[:title], checked: result[:checked] })
end
end
def self.create(params = {})
validates(params) do |result|
if result[:error].nil?
title = params[:title]
checked = params[:checked].to_i == 1
resultID = db.exec("INSERT INTO list_items (title, checked) VALUES ($1, $2)", title, checked)
new({ id: resultID, title: title, checked: checked })
else
new({ error: result[:error] })
end
end
end
def self.validates(params)
if params.nil? || params[:title].nil?
yield({ error: 'Title cannot be empty' })
elsif params[:title].empty?
yield({ error: 'Title cannot be empty' })
else
if params[:title].length > 40
yield({ error: 'Title too long (should less than 40 characters)' })
else
yield({})
end
end
end
end