Created
May 23, 2009 14:54
-
-
Save neerajsingh0101/116650 to your computer and use it in GitHub Desktop.
roll_searchable
This file contains hidden or 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
| class Article < ActiveRecord::Base | |
| end | |
| class User < ActiveRecord::Base | |
| has_many :articles | |
| roll_searchable_for do | |
| searchable_for :first_name | |
| searchable_for :last_name | |
| searchable_for :email, | |
| :condition => "users.email LIKE :search_term AND users.id > 1" | |
| searchable_for :notes | |
| searchable_for 'articles.title', :include => 'articles' | |
| end | |
| end | |
| ActiveRecord::Base.send(:extend,RollSearchable) | |
| module RollSearchable | |
| Searchable = Struct.new :attribute,:condition,:includes | |
| def roll_searchable_for(&blk) | |
| instance_eval(&blk) | |
| end | |
| def searchable_for(attribute,options = {}) | |
| @searchables ||=[] | |
| @searchables << Searchable.new(attribute,options[:condition],options[:include]) | |
| # currently I am building the named_scope after every attribute. It should be refactored to improve performance. | |
| build_named_scope_search | |
| end | |
| def build_named_scope_search | |
| self.named_scope :search, lambda { |search_term| | |
| conditions = @searchables.collect do |searchable| | |
| if searchable.condition | |
| "(#{searchable.condition})" | |
| else | |
| # handle cases like 'articles.title' | |
| if searchable.attribute.to_s.include?('.') | |
| table_name_and_attribute_name = searchable.attribute.to_s | |
| else | |
| table_name_and_attribute_name = self.table_name+'.'+searchable.attribute.to_s | |
| end | |
| "( #{table_name_and_attribute_name} LIKE :search_term)" | |
| end | |
| end | |
| conditions = conditions.join(' OR ') | |
| conditions = [conditions,{:search_term => "%#{search_term}%"}] | |
| includes = @searchables.collect { |searchable| searchable.includes} | |
| includes = includes.flatten.compact | |
| puts includes.inspect | |
| {:conditions => conditions, :include => includes } | |
| } | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment