Module: Mongoid::Extensions::ObjectId::Conversions

Included in:
BSON::ObjectId
Defined in:
lib/mongoid/extensions/object_id/conversions.rb

Overview

Provides conversions to and from BSON::ObjectIds and Strings, Arrays, and Hashes.

Instance Method Summary collapse

Instance Method Details

#convert(klass, object, reject_blank = true) ⇒ BSON::ObjectId, ...

TODO:

Durran: This method can be refactored.

Convert the supplied arguments to object ids based on the class settings.

Examples:

Convert a string to an object id

BSON::ObjectId.convert(Person, "4c52c439931a90ab29000003")

Convert an array of strings to object ids.

BSON::ObjectId.convert(Person, [ "4c52c439931a90ab29000003" ])

Convert a hash of id strings to object ids.

BSON::ObjectId.convert(Person, { :_id => "4c52c439931a90ab29000003" })

Parameters:

  • klass (Class)

    The class to convert the ids for.

  • object (Object, Array, Hash)

    The object to convert.

Returns:

Raises:

  • BSON::InvalidObjectId If using object ids and passed bad strings.

Since:

  • 2.0.0.rc.7



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/mongoid/extensions/object_id/conversions.rb', line 33

def convert(klass, object, reject_blank = true)
  return object if object.is_a?(BSON::ObjectId) || !klass.using_object_ids?
  case object
  when ::String
    return nil if object.blank?
    if object.unconvertable_to_bson?
      object
    else
      BSON::ObjectId.legal?(object) ? BSON::ObjectId.from_string(object) : object
    end
  when ::Array
    object.delete_if { |arg| arg.blank? } if reject_blank
    object.replace(object.map { |arg| convert(klass, arg, reject_blank) })
  when ::Hash
    object.tap do |hash|
      hash.each_pair do |key, value|
        next unless klass.object_id_field?(key)
        hash[key] = convert(klass, value, reject_blank)
      end
    end
  else
    object
  end
end