Last active
December 28, 2015 07:09
-
-
Save adimasuhid/7462623 to your computer and use it in GitHub Desktop.
Active Record Full Text Search Module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FullSearchable | |
def searchable(scope_name, *attrs) | |
raise ArgumentError if attrs.blank? | |
define_singleton_method("#{scope_name}") do |terms| | |
return if terms.blank? | |
composed_scope = self.scoped | |
terms.downcase.split(' ') .each do |term| | |
composed_scope = composed_scope.where(create_query(attrs, term)) | |
end | |
composed_scope | |
end | |
end | |
private | |
def create_query(attributes, term) | |
attrb = "" | |
term = '%' << term << '%' | |
attributes.each do |attr| | |
attrb += " OR " if attrb.present? | |
attrb += "lower(#{attr}) LIKE '#{term}'" | |
end | |
attrb | |
end | |
end | |
#usage: | |
#class Sample | |
# extend FullSearchable | |
# searchable :method_name, :attr1, :attr2... | |
#end | |
# | |
# Sample.method_name("search param") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment