Commit 3c8d42e0726aa85f893e56a48c004778767c79a7

Authored by Andrew Kane
1 parent 74d20c66

Added dates option to return dates for day, week, month, quarter, and year

  1 +## 2.5.2 [unreleased]
  2 +
  3 +- Added `dates` option to return dates for day, week, month, quarter, and year
  4 +
1 ## 2.5.1 5 ## 2.5.1
2 6
3 - Added `group_by_quarter` 7 - Added `group_by_quarter`
lib/groupdate.rb
@@ -9,9 +9,10 @@ module Groupdate @@ -9,9 +9,10 @@ module Groupdate
9 FIELDS = PERIODS 9 FIELDS = PERIODS
10 METHODS = PERIODS.map { |v| :"group_by_#{v}" } 10 METHODS = PERIODS.map { |v| :"group_by_#{v}" }
11 11
12 - mattr_accessor :week_start, :day_start, :time_zone 12 + mattr_accessor :week_start, :day_start, :time_zone, :dates
13 self.week_start = :sun 13 self.week_start = :sun
14 self.day_start = 0 14 self.day_start = 0
  15 + self.dates = false
15 end 16 end
16 17
17 require "groupdate/enumerable" 18 require "groupdate/enumerable"
lib/groupdate/magic.rb
@@ -254,6 +254,8 @@ module Groupdate @@ -254,6 +254,8 @@ module Groupdate
254 I18n.localize(key, format: options[:format], locale: locale) 254 I18n.localize(key, format: options[:format], locale: locale)
255 end 255 end
256 end 256 end
  257 + elsif (options[:dates] || (Groupdate.dates && !options.key?(:dates))) && [:day, :week, :month, :quarter, :year].include?(field)
  258 + lambda { |k| k.to_date }
257 else 259 else
258 lambda { |k| k } 260 lambda { |k| k }
259 end 261 end
test/test_helper.rb
@@ -906,6 +906,13 @@ module TestGroupdate @@ -906,6 +906,13 @@ module TestGroupdate
906 assert_equal 2, User.group_by_day(:created_at, carry_forward: true).count[utc.parse("2014-05-02 00:00:00 UTC")] 906 assert_equal 2, User.group_by_day(:created_at, carry_forward: true).count[utc.parse("2014-05-02 00:00:00 UTC")]
907 end 907 end
908 908
  909 + # dates
  910 +
  911 + def test_dates
  912 + create_user "2014-03-01 12:00:00 UTC"
  913 + assert_equal ({Date.parse("2014-03-01") => 1}), User.group_by_day(:created_at, dates: true).count
  914 + end
  915 +
909 # helpers 916 # helpers
910 917
911 def assert_format(method, expected, format, options = {}) 918 def assert_format(method, expected, format, options = {})