Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Mongoid know the difference between string values and symbol values?

Consider this example:

> x = User.first # or any persisted Mongoid::Document
=> #<User _id: 52014532a6356d1ac9000001, ...>
> x.set :foo, :bar
=> :bar
> x.set :foo2, 'bar'
=> "bar"

Note that "foo" and "foo2" are not declared in Ruby anywhere.

THEN, in a MongoDB shell:

> db.users.findOne({_id: ObjectId('52014532a6356d1ac9000001')})    
{
  "_id" : ObjectId("52014532a6356d1ac9000001"),
  "foo" : "bar",
  "foo2" : "bar",
  ...
}

BUT NOW, back in Ruby:

> x = User.find x.id; nil # to clear out any possibility of metadata on the instance
=> nil
> [x.read_attribute(:foo), x.read_attribute(:foo2)]
=> [:bar, "bar"]

How does it know?

like image 764
lawrence Avatar asked Oct 21 '22 22:10

lawrence


1 Answers

Seens like BSON supports a symbol type for values, googling around I found it:

https://github.com/mongodb/mongo-ruby-driver/wiki/FAQ#FrequentlyAskedQuestions-Ruby-IseethatBSONsupportsasymboltype.DoesthismeanthatIcanstoreRubysymbolsinMongoDB%3F

like image 176
Rafael Oliveira Avatar answered Oct 31 '22 20:10

Rafael Oliveira