Class: Mongoid::Slug::Criteria

Inherits:
Criteria
  • Object
show all
Defined in:
lib/mongoid/slug/criteria.rb

Instance Method Summary collapse

Instance Method Details

#find(*slugs) ⇒ Array<Document>, Document

Find the matching document(s) in the criteria for the provided ids or slugs.

If the document _ids are of the type BSON::ObjectId, and all the supplied parameters are convertible to BSON::ObjectId (via BSON::ObjectId#from_string), finding will be performed via _ids.

If the document has any other type of _id field, and all the supplied parameters are of the same type, finding will be performed via _ids.

Otherwise finding will be performed via slugs.

Examples:

Find by an id.

criteria.find(BSON::ObjectId.new)

Find by multiple ids.

criteria.find([ BSON::ObjectId.new, BSON::ObjectId.new ])

Find by a slug.

criteria.find('some-slug')

Find by multiple slugs.

criteria.find([ 'some-slug', 'some-other-slug' ])

Parameters:

  • slugs (Array<Object>)

    The ids or slugs to search for.

Returns:

  • (Array<Document>, Document)

    The matching document(s).



32
33
34
35
36
# File 'lib/mongoid/slug/criteria.rb', line 32

def find(*slugs)
  return find_by_slug!(*slugs) if look_like_slugs?(*slugs)

  super
end

#find_by_slug!(*slugs) ⇒ Array<Document>, Document

Find the matchind document(s) in the criteria for the provided slugs.

Examples:

Find by a slug.

criteria.find('some-slug')

Find by multiple slugs.

criteria.find([ 'some-slug', 'some-other-slug' ])

Parameters:

  • slugs (Array<Object>...)

    The slugs to search for.

Returns:

  • (Array<Document>, Document)

    The matching document(s).



49
50
51
52
53
# File 'lib/mongoid/slug/criteria.rb', line 49

def find_by_slug!(*slugs)
  slugs = find_args(slugs)
  raise_invalid if slugs.any?(&:nil?)
  for_slugs(slugs).execute_or_raise_for_slugs(slugs)
end

#look_like_slugs?(*slugs) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
61
62
# File 'lib/mongoid/slug/criteria.rb', line 55

def look_like_slugs?(*slugs)
  slugs = find_args(slugs)
  return false unless slugs.all?(String)

  id_field = @klass.fields['_id']
  @slug_strategy ||= id_field.options[:slug_id_strategy] || build_slug_strategy(id_field.type)
  slugs.none? { |slug| @slug_strategy.call(slug) }
end