Date/time scopes for ActiveRecord models you always missed! With proper time-zones support.
# Gemfile
gem "datetime-scopes"
# app/models/my_model.rb
class MyModel < ActiveRecord::Base
datetime_scopes :created_at # with 'datetime' typed attribute
date_scopes :birthday # with 'date' typed attribute
end
Now your model has these scopes:
for created_at | for birthday |
|
|
Examples:
# All records created yesterday (in current `::Time.zone`)
MyModel.created_on_day(Date.yesterday)
# Records created since 11 Sep 2001 (in current `::Time.zone`)
MyModel.created_on_or_after("2001.09.11")
# Records create since 11 Sep 2001 (in New York). Yes, the result may differ to previous example!
MyModel.created_on_or_after("2001.09.11", time_zone: "Eastern Time (US & Canada)")
# Records with birthday in 2015
MyModel.birthday_on_year(Date.new 2015)
You know, when it is Sunday in San Francisco, it is Monday in Manila!
All parameters passed to a date/time scopes are first converted to a
project-specific (::Time.zone
) or specified (time_zone: "XXX"
param) time-zone with the help
of magic ActiveSupport's #in_time_zone
helper. See rake time:zones:all
for
all supported time-zones.
You can pass a default time-zone and custom scopes' prefix to a date(time)_scopes
method:
# app/models/my_model.rb
class MyModel < ActiveRecord::Base
datetime_scopes :created_at, prefix: "issued", time_zone: "Ekaterinburg"
end
# All records created yesterday (in Ekaterinburg)
MyModel.issued_on_day(Date.yesterday)
- Complete pending tests!
- ...
Any feedback is welcome!
Distributed under the MIT License (see LICENSE.txt).
Copyright © 2015. Alexey Chernenkov