/
plays.rb
77 lines (67 loc) · 1.72 KB
/
plays.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
75
76
77
require 'sqlite3'
require 'singleton'
require 'byebug'
class PlayDBConnection < SQLite3::Database
include Singleton
def initialize
super('plays.db')
self.type_translation = true
self.results_as_hash = true
end
end
class Play
attr_accessor :id, :title, :year, :playwright_id
def self.all
data = PlayDBConnection.instance.execute("SELECT * FROM plays")
data.map { |datum| Play.new(datum) }
end
def initialize(options)
@id = options['id']
@title = options['title']
@year = options['year']
@playwright_id = options['playwright_id']
end
def create
raise "#{self} already in database" if self.id
PlayDBConnection.instance.execute(<<-SQL, self.title, self.year, self.playwright_id)
INSERT INTO
plays (title, year, playwright_id)
VALUES
(?, ?, ?)
SQL
self.id = PlayDBConnection.instance.last_insert_row_id
end
def update
raise "#{self} not in database" unless self.id
PlayDBConnection.instance.execute(<<-SQL, self.title, self.year, self.playwright_id, self.id)
UPDATE
plays
SET
title = ?, year = ?, playwright_id = ?
WHERE
id = ?
SQL
end
def self.find_by_title(title)
title_search = PlayDBConnection.instance.execute(<<-SQL, title)
SELECT
*
FROM
plays
WHERE
title = ?
SQL
Play.new(title_search.first)
end
def self.find_by_playwright(name)
name_search = PlayDBConnection.instance.execute(<<-SQL, name)
SELECT
*
FROM
plays
WHERE
playwright_id = (SELECT playwright_id FROM playwrights WHERE name = ?)
SQL
Play.new(name_search.first);
end
end