Skip to content

Instantly share code, notes, and snippets.

@adimasuhid
Last active December 28, 2015 07:09
Show Gist options
  • Save adimasuhid/7462623 to your computer and use it in GitHub Desktop.
Save adimasuhid/7462623 to your computer and use it in GitHub Desktop.
Active Record Full Text Search Module
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