datetime-scopes

A plugin for ActiveRecord which adds very helpful methods for querying records over time ranges (weeks/days/months/years), and it also respects time-zones!

MIT License

Stars
14

Date/time scopes for ActiveRecord models

Date/time scopes for ActiveRecord models you always missed! With proper time-zones support.

Quick start

# 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:

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)

Time-zone support

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.

Additional options

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)

TODO

  • Complete pending tests!
  • ...

Contributing

Any feedback is welcome!

License

Distributed under the MIT License (see LICENSE.txt).

Copyright © 2015. Alexey Chernenkov