Skip to content

Commit

Permalink
Searcher.search の条件判定部分をリファクタリング
Browse files Browse the repository at this point in the history
refs #1510

### 概要
document_type による 処理の振り分け で if文 にベタ書きされていてリーダブルではなかったため、条件判定の処理に名前付けする目的でメソッドに切り出し
また、全ての条件式に document_type を引数として渡すのは DRY ではないため、条件判定のメソッドは lambda を返すようにして if を case に置き換えた
  • Loading branch information
sanfrecce-osaka committed Apr 11, 2020
1 parent 931559b commit 214e427
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions app/models/searcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@ class Searcher
["Docs", :pages]
]

AVAILABLE_TYPES = DOCUMENT_TYPES.map(&:second) - [:all] + [:comments] + [:answers]
AVAILABLE_TYPES = DOCUMENT_TYPES.map(&:second) - %i[all] + %i[comments answers]

class << self
def search(word, document_type: :all)
if document_type == :all
case document_type
when all?
AVAILABLE_TYPES.flat_map { |type| result_for(type, word) }.sort_by { |result| result.created_at }.reverse
elsif model(document_type).include?(Commentable)
when commentable?
[document_type, :comments].flat_map { |type| result_for(type, word, commentable_type: model_name(document_type)) }.sort_by { |result| result.created_at }.reverse
elsif document_type == :questions
when question?
[document_type, :answers].flat_map { |type| result_for(type, word) }
else
result_for(document_type, word).sort_by { |result| result.created_at }.reverse
Expand All @@ -36,6 +37,18 @@ def available_type?(type)
AVAILABLE_TYPES.find { |available_type| available_type == type }.present?
end

def all?
-> (document_type) { document_type == :all }
end

def commentable?
-> (document_type) { model(document_type).include?(Commentable) }
end

def question?
-> (document_type) { document_type == :questions }
end

def model(type)
model_name(type).constantize
end
Expand Down

0 comments on commit 214e427

Please sign in to comment.