mongoid_embedded_list adds methods to embedded documents in mongoid to allow them to be manipulated like an ordered list.
On a recent project I needed to easily order embedded documents. Since Mongoid embedded documents are stored as an array, I decided to write a gem to make it easy to manipulate the order of embedded documents.
To install, add the gem to your Gemfile:
To add the functionality to your embedded document, use
include Mongoid::EmbeddedList in your embedded document.
class List include Mongoid::Document embeds_many :items end class Item include Mongoid::Document include Mongoid::EmbeddedList embedded_in :list end
Now you can change the order of your embedded documents:
item.move_up # moves the item up in the list item.last # check if the item is the last item item.move_to_top # move the item to the top of the list
The complete list of methods are as follows:
first? # check if the item is the first item last? # check if the item is the last item move_to_top # move item to the top of the list move_to_bottom # move item to the bottom of the list move_up # move the item up one position in the list move_down # move the item down one position in the list move_before(other) # move the item to the position before other move_after(other) # move the item to the position after other move_to(position) # move item to position in the list, 1-based index
- I'm not sure if this is the best implementation of this. Part of me thinks that the collection should be managed by the parent document. Due to the way Mongoid, and I believe MongoDB, are designed, the collection has to be recreated after every modification of the list. I'm not sure what the performance impact is of this.
- This is my first attempt at a gem, so any comments, suggestions or patches are welcome.
Check out https://github.com/trait/mongoid_embedded_list and fork away!