-
Notifications
You must be signed in to change notification settings - Fork 8
/
comment.rb
91 lines (73 loc) · 1.88 KB
/
comment.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
# frozen_string_literal: true
require_relative 'base'
DB.create_table?(:comments) do
primary_key :id
foreign_key :author_id, :authors, index: true, on_delete: :cascade
foreign_key :post_slug, :posts, type: String, index: true, on_delete: :cascade, on_update: :cascade
String :body, text: true, null: false
Float :created_at
Float :updated_at
end
class Comment < Sequel::Model
plugin :auto_validations, not_null: :presence
plugin :timestamps
set_allowed_columns :body
many_to_one :author
many_to_one :post
def validate
super
validates_not_null [:author, :post]
end
end
class CommentSerializer < BaseSerializer
attribute :body
has_one :author
has_one :post
end
CommentController = proc do
helpers do
def find(id)
Comment.with_pk(id.to_i)
end
def role
Array(super).tap do |a|
a << :owner if resource&.author == current_user
end
end
end
show do
next resource, include: 'author'
end
create(roles: :logged_in) do |attr|
comment = Comment.new(attr)
comment.save(validate: false)
next_pk comment
end
update(roles: %i[owner superuser]) do |attr|
resource.set(attr)
resource.save_changes(validate: false)
end
destroy(roles: %i[owner superuser]) do
resource.destroy
end
has_one :post do
pluck do
resource.post
end
graft(roles: :superuser, sideload_on: :create) do |rio|
resource.post = Post.with_pk!(rio[:id].to_i)
resource.save_changes(validate: !sideloaded?)
end
end
has_one :author do
pluck do
resource.author
end
graft(roles: :superuser, sideload_on: :create) do |rio|
halt 403, 'You may only assign yourself as comment author!' \
unless role?(:superuser) || rio[:id].to_i == current_user.id
resource.author = Author.with_pk!(rio[:id].to_i)
resource.save_changes(validate: !sideloaded?)
end
end
end