Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract `Moped::BSON::Document` attributes in Ruby hash

In Mongoid 3.0.21, how to get all model's attributes as a plain Ruby Hash?

Calling either #attributes or #raw_attributes returns Moped::BSON::Document. While it actually extends Hash, several hash method does not work as expected. Particularly #except returns unmodified self, not hash with given keys stripped off.

Update: Moped::BSON::Document properly inherits behavior of Hash. I was trying to name attributes with symbols, not strings, that's why #except didn't work. Shortly: do except('pictures'), not except(:pictures).

like image 631
skalee Avatar asked Dec 07 '22 09:12

skalee


2 Answers

Hash[e.attributes]

where e is your model instance

like image 110
cthulhu Avatar answered Dec 18 '22 10:12

cthulhu


I apologize for bumping something so old, but I wanted to leave this here for myself and all the future people who run into this same issue. I am using the Mongoid ORM for Rails, which uses Moped internally for its interaction with MongoDB.

This gem has now saved me hours and hours of manually converting things to Hash or HashWithIndifferentAccess: https://github.com/mindscratch/mongoid-indifferent-access.

Essentially it seems to have some sort of pre-return hook that automatically converts all documents coming from MongoDB to type HashWithIndifferentAccess.

Not looking for points on this. Just wanted to leave this here because it is the top Google result for this issue and it saved me from going insane.

like image 45
Pierce Avatar answered Dec 18 '22 09:12

Pierce