Module: Mongoid::LocalizedSlug::Criterion

Defined in:
lib/mongoid/localized_slug/criterion.rb

Instance Method Summary collapse

Instance Method Details

#for_ids(*ids) ⇒ Object

Override Mongoid’s finder to use slug or id



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/mongoid/localized_slug/criterion.rb', line 3

def for_ids(*ids)
  return super unless @klass.ancestors.include?(Mongoid::LocalizedSlug)

  # We definitely don't want to rescue at the same level we call super above -
  # that would risk applying our slug behavior to non-slug objects, in the case
  # where their id conversion fails and super raises BSON::InvalidObjectId
  begin
    # note that there is a small possibility that a client could create a slug that
    # resembles a BSON::ObjectId
    ids.flatten!
    BSON::ObjectId.from_string(ids.first) unless ids.first.is_a?(BSON::ObjectId)
    super # Fallback to original Mongoid::Criterion::Optional
  rescue BSON::InvalidObjectId
    # slug
    if ids.size > 1
      where(@klass.slug_name.to_sym.in => ids)
    else
      where(@klass.slug_name => ids.first)
    end
  end
end