Sha256: d87065cbde72ddb7a4d024b9e71f07519a041eab261520e34067e77117af93e6

Contents?: true

Size: 959 Bytes

Versions: 2

Compression:

Stored size: 959 Bytes

Contents

module Mongoid::Search
  extend ActiveSupport::Concern
  
  included do
    cattr_accessor :search_fields, :match
  end
  
  module ClassMethods #:nodoc:
    # Set a field or a number of fields as sources for search
    def search_in(*args)
      options = args.last.is_a?(Hash) && (args.last.keys.first == :match) ? args.pop : {}
      self.match = options[:match] || :any
      self.search_fields = args

      field :_keywords, :type => Array
      index :_keywords
      
      before_save :set_keywords
    end
    
    def search(query)
      self.send("#{self.match.to_s}_in", :_keywords => KeywordsExtractor.extract(query).map { |q| /#{q}/i })
    end
  end
  
  private
  
  def set_keywords
    self._keywords = self.search_fields.map do |field|
      field.is_a?(Hash) ? self.send(field.keys.first).map(&field.values.first).map { |t| KeywordsExtractor.extract t } : KeywordsExtractor.extract(self.send(field))
    end.flatten.compact.uniq
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mongoid_search-0.1.1 lib/mongoid_search/mongoid_search.rb
mongoid_search-0.1.0 lib/mongoid_search/mongoid_search.rb