Sha256: f090f1e76c5f986c3f4bb0489fe5eee0f3d91681e4bfbf9b4ab7b77194f3127d

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

require 'sunspot'
require 'mongoid'
require 'sunspot/rails'

module Sunspot
  module Mongoid2
    def self.included(base)
      base.class_eval do
        extend Sunspot::Rails::Searchable::ActsAsMethods
        extend Sunspot::Mongoid2::ActsAsMethods
        Sunspot::Adapters::DataAccessor.register(DataAccessor, base)
        Sunspot::Adapters::InstanceAdapter.register(InstanceAdapter, base)
      end
    end

    module ActsAsMethods
      # ClassMethods isn't loaded until searchable is called so we need
      # call it, then extend our own ClassMethods.
      def searchable (opt = {}, &block)
        super 
        extend ClassMethods
      end
    end

    module ClassMethods
      # The sunspot solr_index method is very dependent on ActiveRecord, so
      # we'll change it to work more efficiently with Mongoid.
      def solr_index(opt={})
        Sunspot.index!(all)
      end
    end


    class InstanceAdapter < Sunspot::Adapters::InstanceAdapter
      def id
        @instance.id
      end
    end

    class DataAccessor < Sunspot::Adapters::DataAccessor
      def load(id)
        @clazz.find(::Moped::BSON::ObjectId.from_string(id)) rescue nil
      end

      def load_all(ids)
        @clazz.where(:_id.in => ids.map { |id| ::Moped::BSON::ObjectId.from_string(id) })
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sunspot_mongoid2-0.5.1.5 lib/sunspot/mongoid2.rb