Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dblock/ded50b61db49baf32a8d to your computer and use it in GitHub Desktop.
Save dblock/ded50b61db49baf32a8d to your computer and use it in GitHub Desktop.
require 'mongoid'
require 'mongoid_collection_snapshot'
Mongoid.load!("mongoid.yml", :development)
class Widget
include Mongoid::Document
end
class Gadget
include Mongoid::Document
end
class WidgetAndGadget
include Mongoid::Document
belongs_to :widget, inverse_of: nil
belongs_to :gadget, inverse_of: nil
def self.pair!
WidgetAndGadget.destroy_all
Widget.all.each do |widget|
Gadget.all.each do |gadget|
WidgetAndGadget.create!(widget: widget, gadget: gadget) if Random.rand(2) == 1
end
end
end
def self.pair_incrementally!
widgets_and_gadgets = []
Widget.all.each do |widget|
Gadget.all.each do |gadget|
next unless Random.rand(2) == 1
widget = WidgetAndGadget.where(widget: widget, gadget: gadget).first
widget ||= WidgetAndGadget.create!(widget: widget, gadget: gadget)
widgets_and_gadgets << widget
end
end
(WidgetAndGadget.all.to_a - widgets_and_gadgets).each do |pair|
pair.destroy
end
end
end
class WidgetsAndGadgets
include Mongoid::CollectionSnapshot
document do
belongs_to :widget, inverse_of: nil
belongs_to :gadget, inverse_of: nil
end
def build
Widget.all.each do |widget|
Gadget.all.each do |gadget|
next unless Random.rand(2) == 1
collection_snapshot.insert(widget_id: widget.id, gadget_id: gadget.id)
end
end
end
end
=begin
Widget.delete_all
Gadget.delete_all
10.times { Widget.create! }
10.times { Gadget.create! }
WidgetAndGadget.pair!
puts "#{WidgetAndGadget.count} widgets and gadgets paired!"
WidgetAndGadget.pair_incrementally!
puts "#{WidgetAndGadget.count} widgets and gadgets paired incrementally!"
=end
index1 = WidgetsAndGadgets.create!
puts "#{index1.collection_snapshot.find.count} widgets and gadgets paired incrementally!"
index2 = WidgetsAndGadgets.create!
puts "#{index2.collection_snapshot.find.count} widgets and gadgets paired incrementally!"
WidgetsAndGadgets.latest.documents.each do |pair|
puts "#{pair.widget} x #{pair.gadget}"
end
source 'http://rubygems.org'
gem 'mongoid'
gem 'mongoid_collection_snapshot', github: 'dblock/mongoid_collection_snapshot', branch: 'collection-snapshot-mongoid'
development:
sessions:
default:
database: first-class-mongoid-queries
hosts:
- localhost:27017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment