Class: Mongoid::Slug::Criteria

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

Instance Method Summary collapse

Instance Method Details

#find(*args) ⇒ 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:

  • args (Array<Object>)

    The ids or slugs to search for.

Returns:

  • (Array<Document>, Document)

    The matching document(s).



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

def find(*args)
  look_like_slugs?(args.__find_args__) ? find_by_slug!(*args) : super
end

#find_by_slug!(*args) ⇒ 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:

  • args (Array<Object>)

    The slugs to search for.

Returns:

  • (Array<Document>, Document)

    The matching document(s).



47
48
49
50
51
# File 'lib/mongoid/slug/criteria.rb', line 47

def find_by_slug!(*args)
  slugs = args.__find_args__
  raise_invalid if slugs.any?(&:nil?)
  for_slugs(slugs).execute_or_raise_for_slugs(slugs, args.multi_arged?)
end

#look_like_slugs?(args) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
56
57
58
59
# File 'lib/mongoid/slug/criteria.rb', line 53

def look_like_slugs?(args)
  return false unless args.all? { |id| id.is_a?(String) }

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