mongodb/mongo-ruby-driver — pull request #101 by farrel (2012-05-25 23:55:22+00:00)
Title: Added BSON::ObjectId#to_ary

While working on a Padrino app I noticed that when I was trying to associate two MongoMapper documents together with a select drop down that when the form was displayed for editing using:

```ruby
f.select( :organisation_id, :collection => Organisation.all, :fields => [ :name, :id ])
```

it would fail to correctly select the correct due to the following [piece of code](https://github.com/padrino/padrino-framework/blob/master/padrino-helpers/lib/padrino-helpers/form_helpers.rb#L780):

```ruby
def option_is_selected?(value, caption, selected_values)
Array(selected_values).any? do |selected|
[value.to_s, caption.to_s].include?(selected.to_s)
end
end
```

Kernel#Array is commonly used when we are unsure if a variable is holding an single object or a collection (in the case above there could be a single selected value or an array of selected values), so that it may be handled in a uniform manner with code reuse. It will first call #to_ary, then #to_a and finally wrap the collection in an Array.

```ruby
Array(1).join(", ") # => "1"
Array([1,2]).join(", ") # =>"1, 2"
```

Because BSON::ObjectId defines #to_a when a collection of ObjectIds is passed to Array() we iterate over the ObjectIds as expected but when a singular ObjectId is passed to Array() the @data array is returned.

```ruby
Array( object_id_1 ).size # => 12 - length of @data array
Array([object_id_1, object_id_2]).size # =>2 - length of passed in array
```

I've defined BSON::ObjectId#to_ary as simply as

```ruby
def to_ary
[self]
end
```

and added a corresponding test. All existing tests run successfully.