-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.rb
111 lines (91 loc) · 1.99 KB
/
user.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
require_relative 'saveable'
class User
include Saveable
def self.all
results = QuestionDatabase.instance.execute('SELECT * FROM users')
results.map { |result| User.new(result) }
end
def self.find_by_id(id)
results = QuestionDatabase.instance.execute(<<-SQL, id)
SELECT
*
FROM
users
WHERE
id = ?
SQL
User.new(results.first)
end
def self.find_by_name(fname, lname)
results = QuestionDatabase.instance.execute(<<-SQL, fname, lname)
SELECT
*
FROM
users
WHERE
fname = ? AND
lname = ?
SQL
User.new(results.first)
end
attr_accessor :fname, :lname
attr_reader :id
def initialize(options = {})
@id = options['id']
@lname = options['lname']
@fname = options['fname']
end
# def save
# if id.nil?
# QuestionDatabase.instance.execute(<<-SQL, fname, lname)
# INSERT INTO
# users(fname, lname)
# VALUES
# (?, ?)
# SQL
#
# @id = QuestionDatabase.instance.last_insert_row_id
# else
# QuestionDatabase.instance.execute(<<-SQL, fname, lname, self.id)
# UPDATE
# users
# SET
# fname = ?, lname = ?
# WHERE
# id = ?
# SQL
#
# end
#
# nil
# end
def name
"#{fname} #{lname}"
end
def authored_questions
Question::find_by_author_id(self.id)
end
def authored_replies
Reply::find_by_user_id(self.id)
end
def followed_questions
QuestionFollow::followed_questions_for_user_id(self.id)
end
def liked_question
QuestionLike::liked_questions_for_user_id(self.id)
end
def average_karma
result = QuestionDatabase.instance.execute(<<-SQL, self.id)
SELECT
COUNT(question_likes.question_id) /
CAST(COUNT(DISTINCT questions.id) AS FLOAT) AS karma
FROM
questions
LEFT OUTER JOIN
question_likes ON questions.id = question_likes.question_id
WHERE
questions.user_id = ?
SQL
result.first['karma']
end
end