我的搜索方法又臭又肿,我需要一些帮助来重构它。我是 Ruby 新手,我还没有弄清楚如何有效地利用它,这导致了像这样的臃肿方法:
# discussion.rb
def self.search(params)
# If there is a search query, use Tire gem for fulltext search
if params[:query].present?
tire.search(load: true) do
query { string params[:query] }
end
# Otherwise grab all discussions based on category and/or filter
else
# Grab all discussions and include the author
discussions = self.includes(:author)
# Filter by category if there is one specified
discussions = discussions.where(category: params[:category]) if params[:category]
# If params[:filter] is provided, user it
if params[:filter]
case params[:filter]
when 'hot'
discussions = discussions.open.order_by_hot
when 'new'
discussions = discussions.open.order_by_new
when 'top'
discussions = discussions.open.order_by_top
else
# If params[:filter] does not match the above three states, it's probably a status
discussions = discussions.order_by_new.where(status: params[:filter])
end
else
# If no filter is passed, just grab discussions by hot
discussions = discussions.open.order_by_hot
end
end
end
STATUSES = {
question: %w[answered],
suggestion: %w[started completed declined],
problem: %w[solved]
}
scope :order_by_hot, order('...') DESC, created_at DESC")
scope :order_by_new, order('created_at DESC')
scope :order_by_top, order('votes_count DESC, created_at DESC')
这是一个可以按类别过滤(或不过滤)的讨论模型:question
、problem
、suggestion
。
所有讨论或单个类别可以通过hot
、new
、votes
或进一步过滤status
。状态是模型中的一个哈希值,它有几个取决于类别的值(状态过滤器仅在 params[:category] 存在时出现)。
使事情复杂化的是使用轮胎的全文搜索功能
但我的控制器看起来又漂亮又整洁:
def index
@discussions = Discussion.search(params)
end
我可以把它干掉/重构一下,也许使用元编程或块?我设法将其从控制器中提取出来,但随后就没有想法了。我对 Ruby 的了解还不够深入,无法更进一步。