Skip to content

Commit

Permalink
Merge pull request #150 from publify/clean-up-search-scope
Browse files Browse the repository at this point in the history
Make Content.searchstring scope code more transparent
  • Loading branch information
mvz authored Jun 28, 2024
2 parents 363fea5 + 7ccd91f commit 985e089
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions app/models/content.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,15 @@ class Content < ApplicationRecord
scope :drafts, -> { where(state: "draft").order("created_at DESC") }
scope :no_draft, -> { where.not(state: "draft").order("published_at DESC") }
scope :searchstring, lambda { |search_string|
result = where(state: "published")

tokens = search_string.split(" ").map { |c| "%#{c.downcase}%" }
matcher = "(LOWER(body) LIKE ? OR LOWER(extended) LIKE ? OR LOWER(title) LIKE ?)"
template = "state = ? AND #{([matcher] * tokens.size).join(" AND ")}"
where(template, "published", *tokens.map { |token| [token] * 3 }.flatten)
tokens.each do |token|
result = result
.where("(LOWER(body) LIKE ? OR LOWER(extended) LIKE ? OR LOWER(title) LIKE ?)",
token, token, token)
end
result
}

scope :published_at_like, lambda { |date_at|
Expand Down

0 comments on commit 985e089

Please sign in to comment.