Created
November 9, 2010 21:06
-
-
Save JonKernPA/669805 to your computer and use it in GitHub Desktop.
This shows an odd quirk of the date 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 'rubygems' | |
require 'mongo_mapper' | |
MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017, :logger => Logger.new(STDOUT)) | |
# MongoMapper.connection = Mongo::Connection.new('127.0.0.1', 27017) | |
MongoMapper.database = 'testing' | |
class Person | |
include MongoMapper::Document | |
attr_accessible(:name, :dob) | |
# Attributes :::::::::::::::::::::::::::::::::::::::::::::::::::::: | |
key :name, String | |
key :dob, Time | |
def age | |
now = Time.now.utc.to_date | |
now.year - dob.year - ((now.month > dob.month || (now.month == dob.month && now.day >= dob.day)) ? 0 : 1) | |
end | |
end | |
Person.destroy_all() | |
p60 = Person.create( :name => "Foghorn", :dob => Time.parse((Date.today - 60.years).to_s)) | |
p50p = Person.create( :name => "Bugs", :dob => Time.parse(Date.new(1960,1,1).to_s)) | |
p50 = Person.create( :name => "Bugs2", :dob => Time.parse((Date.today - 50.years).to_s)) | |
p40 = Person.create( :name => "Sylvester", :dob => Time.parse((Date.today - 40.years).to_s)) | |
p10 = Person.create( :name => "Elmer", :dob => Time.parse((Date.today - 10.years).to_s)) | |
p2 = Person.create( :name => "Baby A", :dob => Time.parse((Date.today - 2.years).to_s)) | |
t = Time.now - 3.years | |
# Look for those older than 3 years | |
older = Person.where(:dob.lte => t).all | |
# Look for those under 3 years | |
younger = Person.where(:dob.gt => t).all | |
puts "-"*25 | |
ppl = Person.all | |
ppl.each do |p| | |
puts "#{p.name}, #{p.age} yrs" | |
end | |
puts "*"*25 | |
puts "Older than 3: " | |
unless older.nil? || older.empty? | |
older.each do |p| | |
puts "\t#{p.name}, #{p.age} yrs" | |
end | |
else | |
puts "\tNone" | |
end | |
puts "Younger than 3: " | |
unless younger.nil? || younger.empty? | |
younger.each do |p| | |
puts "\t#{p.name}, #{p.age} yrs" | |
end | |
else | |
puts "\tNone" | |
end | |
puts "-"*25 |
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
------------------------- | |
Foghorn, 60 yrs | |
Bugs, 50 yrs | |
Bugs2, 50 yrs | |
Sylvester, 40 yrs | |
Elmer, 10 yrs | |
Baby A, 2 yrs | |
************************* | |
Older than 3: | |
Sylvester, 40 yrs | |
Elmer, 10 yrs | |
Younger than 3: | |
Foghorn, 60 yrs | |
Bugs, 50 yrs | |
Bugs2, 50 yrs | |
Baby A, 2 yrs | |
------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment