work on refactoring search

This commit is contained in:
albert
2013-01-08 15:53:21 -05:00
parent 80f34d08d9
commit 13271e9bf5
19 changed files with 152 additions and 45 deletions

View File

@@ -14,10 +14,8 @@ class Artist < ActiveRecord::Base
accepts_nested_attributes_for :wiki_page
attr_accessible :body, :name, :url_string, :other_names, :group_name, :wiki_page_attributes, :notes, :is_active, :as => [:member, :privileged, :contributor, :janitor, :moderator, :default, :admin]
attr_accessible :is_banned, :as => :admin
scope :url_match, lambda {|string| where(["id in (?)", Artist.find_all_by_url(string).map(&:id)])}
scope :other_names_match, lambda {|string| where(["other_names_index @@ to_tsquery('danbooru', ?)", Artist.normalize_name(string)])}
scope :name_equals, lambda {|string| where("name = ?", string)}
search_methods :url_match, :other_names_match
scope :active, where("is_active = true")
scope :banned, where("is_banned = true")
module UrlMethods
extend ActiveSupport::Concern
@@ -192,6 +190,71 @@ class Artist < ActiveRecord::Base
end
end
module SearchMethods
extend ActiveSupport::Concern
module ClassMethods
def url_matches(string)
matches = find_all_by_url(string).map(&:id)
if matches.any?
where("id in (?)", matches)
else
where("false")
end
end
def other_names_match(string)
where("other_names_index @@ to_tsquery('danbooru', ?)", Artist.normalize_name(string))
end
def group_name_matches(name)
stripped_name = normalize_name(name).to_escaped_for_sql_like
where("group_name LIKE ? ESCAPE E'\\\\'", stripped_name)
end
def name_matches(name)
stripped_name = normalize_name(name).to_escaped_for_sql_like
where("name LIKE ? ESCAPE E'\\\\'", stripped_name)
end
def any_name_matches(name)
stripped_name = normalize_name(name).to_escaped_for_sql_like
where("(name LIKE ? ESCAPE E'\\\\' OR other_names_index @@ to_tsquery('danbooru', ?))", stripped_name, normalize_name(name))
end
def search(params)
q = active
case params[:name]
when /^http/
q = q.url_matches(params[:name])
when /name:(.+)/
q = q.name_matches($1)
when /other:(.+)/
q = q.other_names_match($1)
when /group:(.+)/
q = q.group_name_matches($1)
when /status:banned/
q = q.banned
when /./
q = q.any_name_matches(params[:name])
end
if params[:id]
q = q.where("id = ?", params[:id])
end
q
end
end
end
include UrlMethods
include NameMethods
include GroupMethods
@@ -200,6 +263,7 @@ class Artist < ActiveRecord::Base
include NoteMethods
include TagMethods
include BanMethods
include SearchMethods
def status
if is_banned?