Created
July 25, 2013 13:39
-
-
Save jimjh/6079724 to your computer and use it in GitHub Desktop.
mongoid complex query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'mongoid' | |
require 'fabrication' | |
Mongoid::Config.load_configuration({ | |
sessions: { | |
default: { | |
hosts: ['localhost:27017'], | |
database: 'local' | |
} | |
} | |
}) | |
class MyModel | |
include Mongoid::Document | |
field :enabled, type: Boolean | |
field :start_date, type: DateTime | |
field :end_date, type: DateTime | |
def self.active | |
start_date = Date.today | |
end_date = Date.tomorrow | |
where( | |
enabled: true, | |
:$or => [ | |
{:start_date.lte => start_date, :end_date.gte => end_date}, | |
{:start_date => nil, :end_date.gte => end_date}, | |
{:start_date.lte => start_date, :end_date => nil}, | |
{:start_date => nil, :end_date => nil}, | |
] | |
) | |
end | |
def self.buggy_active | |
start_date = Date.today | |
end_date = Date.tomorrow | |
where( | |
:$and => [ | |
enabled: true, | |
:$or => [ | |
{ start_date: nil }, | |
{ :start_date.lte => start_date } | |
], | |
:$or => [ | |
{ end_date: nil }, | |
{ :end_date.gte => end_date } | |
] | |
] | |
) | |
end | |
end | |
Fabricator(:model, class_name: MyModel) | |
Fabricator(:active_model, from: :model) do | |
enabled true | |
end | |
describe '.active' do | |
let!(:disabled){ Fabricate(:model, enabled: false, name: 'disabled') } | |
let!(:enabled_without_date){ Fabricate(:active_model, name: 'enabled_without_date') } | |
let!(:past){ Fabricate(:active_model, start_date: 1.week.ago, end_date: Date.yesterday, name: 'past') } | |
let!(:current){ Fabricate(:active_model, start_date: Date.today, end_date: Date.tomorrow, name: 'current') } | |
let!(:future){ Fabricate(:active_model, start_date: Date.tomorrow, end_date: 1.week.from_now, name: 'future') } | |
after :each do | |
Moped::Session.new(['localhost:27017']).with(database: 'local') do |_session| | |
_session.drop | |
end | |
end | |
it 'returns only enabled and within the current time' do | |
MyModel.count.should == 5 | |
models = MyModel.active.to_a | |
models.should_not be_empty | |
models.should_not include disabled | |
models.should_not include future | |
models.should_not include past | |
models.should include enabled_without_date | |
models.should include current | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment