Skip to content

Commit a6155fb

Browse files
committed
Extract search logic to a private method
1 parent 9844787 commit a6155fb

File tree

1 file changed

+22
-21
lines changed

1 file changed

+22
-21
lines changed

app/controllers/messages_controller.rb

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,29 +3,11 @@ class MessagesController < ApplicationController
33

44
# GET /messages
55
def index
6-
query = params[:q]
7-
unless query
8-
@messages = []
9-
10-
render :search
11-
return
12-
end
13-
14-
page = params[:page].to_i
15-
list_ids = get_list_ids(params)
16-
if list_ids.empty?
17-
raise "Need to select at least one list"
18-
end
19-
20-
# %> and <-> are defined by pg_trgm.
21-
# https://www.postgresql.org/docs/17/pgtrgm.html
22-
message_where = if Rails.env.production?
23-
Message.where('body %> ? AND list_id IN (?)', query, list_ids)
24-
.order(Arel.sql('body <-> ?', query))
6+
if (query = params[:q])
7+
search query
258
else
26-
Message.where('body LIKE ? AND list_id IN (?)', "%#{query}%", list_ids)
9+
@messages = []
2710
end
28-
@messages = message_where.offset(page * PER_PAGE).limit(PER_PAGE)
2911

3012
render :search
3113
end
@@ -41,6 +23,7 @@ def show
4123
end
4224

4325
private
26+
4427
def get_list_ids(params)
4528
list_ids = []
4629
['ruby-talk', 'ruby-core', 'ruby-list', 'ruby-dev'].each do |name|
@@ -50,4 +33,22 @@ def get_list_ids(params)
5033
end
5134
list_ids
5235
end
36+
37+
def search(query)
38+
page = params[:page].to_i
39+
list_ids = get_list_ids(params)
40+
if list_ids.empty?
41+
raise "Need to select at least one list"
42+
end
43+
44+
# %> and <-> are defined by pg_trgm.
45+
# https://www.postgresql.org/docs/17/pgtrgm.html
46+
message_where = if Rails.env.production?
47+
Message.where('body %> ? AND list_id IN (?)', query, list_ids)
48+
.order(Arel.sql('body <-> ?', query))
49+
else
50+
Message.where('body LIKE ? AND list_id IN (?)', "%#{query}%", list_ids)
51+
end
52+
@messages = message_where.offset(page * PER_PAGE).limit(PER_PAGE)
53+
end
5354
end

0 commit comments

Comments
 (0)