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, args, 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" })

Raises:

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

Since:

  • 2.0.0.rc.7

Parameters:

  • The class to convert the ids for.

  • The object to convert.

Returns:

  • The converted object ids.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/mongoid/extensions/object_id/conversions.rb', line 65

def convert(klass, args, reject_blank = true)
  return args if args.is_a?(BSON::ObjectId) || !klass.using_object_ids?
  case args
  when ::String
    return nil if args.blank?
    if args.is_a?(Mongoid::Criterion::Unconvertable)
      args
    else
      BSON::ObjectId.from_string(args)
    end
  when ::Array
    args = args.reject(&:blank?) if reject_blank
    args.map do |arg|
      convert(klass, arg, reject_blank)
    end
  when ::Hash
    args.tap do |hash|
      hash.each_pair do |key, value|
        next unless key.to_s =~ /id/
        begin
          hash[key] = convert(klass, value, reject_blank)
        rescue BSON::InvalidObjectId; end
      end
    end
  else
    args
  end
end

#get(value) ⇒ BSON::ObjectId

Get the BSON::ObjectId value.

Examples:

Get the value.

BSON::ObjectId.set(BSON::ObjectId.new)

Since:

  • 1.0

Parameters:

  • The value to get.

Returns:

  • The value.



38
39
40
# File 'lib/mongoid/extensions/object_id/conversions.rb', line 38

def get(value)
  value
end

#set(value) ⇒ BSON::ObjectId

Set the BSON::ObjectId value.

Examples:

Set the value.

BSON::ObjectId.set("4c52c439931a90ab29000003")

Since:

  • 1.0

Parameters:

  • The value to set.

Returns:

  • The set value.



20
21
22
23
24
25
26
# File 'lib/mongoid/extensions/object_id/conversions.rb', line 20

def set(value)
  if value.is_a?(::String)
    BSON::ObjectId.from_string(value) unless value.blank?
  else
    value
  end
end