artsy / garner

A set of Rack middleware and cache helpers that implement various caching strategies.
MIT License
343 stars 24 forks source link

Fixed #47: use a database index when generating proxy binding in Garner::Mixins::Mongoid::Identity with multiple Garner.config.mongoid_identity_fields. #49

Closed dblock closed 11 years ago

dblock commented 11 years ago

This is just the index part of the fix in https://github.com/artsy/garner/pull/48.

fancyremarker commented 11 years ago

Thanks!

dblock commented 11 years ago

Fyi, if you have Garner.config.mongoid_identity_fields = [:_id, :_slugs] with something like Mongoid::Slug, use this monkey patch if you want to override the behavior in your own code and avoid the $or query.

module Garner
  module Mixins
    module Mongoid
      class Identity
        private

        def self.conditions_for(klass, handle)
          # optimize away the query from an $or to a find where appropriate
          # in the case of Gravity _id and _slugs can be used independently
          # and we can never have a non BSON _id and valid BSON IDs are redundant with _id inside _slugs
          conditions = Moped::BSON::ObjectId.legal?(handle) ? { _id: handle } : { _slugs: handle }

          # _type conditions
          selector = klass.where({})
          conditions.merge!(selector.send(:type_selection)) if selector.send(:type_selectable?)

          conditions
        end
      end
    end
  end
end