1
1
class PostsController < ApplicationController
2
- before_action :set_post , only : %i[ show edit update destroy ]
2
+ before_action :enable_caching , only : %i[ index show new edit ]
3
+ skip_before_action :verify_authenticity_token
3
4
4
5
# GET /posts
5
6
def index
@@ -8,6 +9,7 @@ def index
8
9
9
10
# GET /posts/1
10
11
def show
12
+ @post = Post . find ( params [ :id ] )
11
13
end
12
14
13
15
# GET /posts/new
@@ -17,42 +19,59 @@ def new
17
19
18
20
# GET /posts/1/edit
19
21
def edit
22
+ @post = Post . find ( params [ :id ] )
20
23
end
21
24
22
25
# POST /posts
23
26
def create
24
27
@post = Post . new ( post_params )
25
28
26
29
if @post . save
27
- redirect_to @post , notice : "Post was successfully created."
30
+ CachedUrl . expire_by_tags ( [ "posts:all" ] )
31
+ redirect_to post_url ( @post , nocache : true ) , notice : "Post was successfully created."
28
32
else
29
33
render :new , status : :unprocessable_entity
30
34
end
31
35
end
32
36
33
37
# PATCH/PUT /posts/1
34
38
def update
39
+ @post = Post . find ( params [ :id ] )
40
+
35
41
if @post . update ( post_params )
36
- redirect_to @post , notice : "Post was successfully updated."
42
+ CachedUrl . expire_by_tags ( [ "posts:all" , "posts:#{ @post . id } " ] )
43
+ redirect_to post_url ( @post , nocache : true ) , notice : "Post was successfully updated."
37
44
else
38
45
render :edit , status : :unprocessable_entity
39
46
end
40
47
end
41
48
42
49
# DELETE /posts/1
43
50
def destroy
44
- @post . destroy!
45
- redirect_to posts_url , notice : "Post was successfully destroyed." , status : :see_other
51
+ post = Post . find ( params [ :id ] )
52
+
53
+ post . destroy!
54
+
55
+ CachedUrl . expire_by_tags ( [ "posts:all" , "posts:#{ post . id } " ] )
56
+
57
+ redirect_to posts_url ( nocache : true ) , notice : "Post was successfully destroyed." , status : :see_other
46
58
end
47
59
48
60
private
49
- # Use callbacks to share common setup or constraints between actions.
50
- def set_post
51
- @post = Post . find ( params [ :id ] )
52
- end
53
61
54
- # Only allow a list of trusted parameters through.
55
- def post_params
56
- params . require ( :post ) . permit ( :title , :body )
57
- end
62
+ def post_params
63
+ params . require ( :post ) . permit ( :title , :body )
64
+ end
65
+
66
+ def enable_caching
67
+ return if params . key? ( :nocache )
68
+
69
+ # don't cache cookies (note: Cloudflare won't cache responses with cookies)
70
+ request . session_options [ :skip ] = true
71
+
72
+ tags = action_name == "index" ? [ "section:posts" , "posts:all" ] : [ "section:posts" , "posts:#{ params [ :id ] } " ]
73
+
74
+ CachedUrl . upsert ( { url : request . url , tags :, expires_at : 1 . hour . from_now } , unique_by : :url )
75
+ expires_in 1 . hour , public : true
76
+ end
58
77
end
0 commit comments