Commit d40c46124122ecbbfefa5c6820d57ca694cf2274

Authored by Andrew Kane
1 parent d465cd4d

Fix for group_by_period with associations - closes #139

lib/groupdate/enumerable.rb
... ... @@ -11,13 +11,20 @@ module Enumerable
11 11 end
12 12 end
13 13  
14   - def group_by_period(period, options = {}, &block)
15   - # to_sym is unsafe on user input, so convert to strings
16   - permitted_periods = ((options[:permit] || Groupdate::PERIODS).map(&:to_sym) & Groupdate::PERIODS).map(&:to_s)
17   - if permitted_periods.include?(period.to_s)
18   - send("group_by_#{period}", options, &block)
  14 + def group_by_period(*args, &block)
  15 + if block || !respond_to?(:scoping)
  16 + period = args[0]
  17 + options = args[1] || {}
  18 +
  19 + # to_sym is unsafe on user input, so convert to strings
  20 + permitted_periods = ((options[:permit] || Groupdate::PERIODS).map(&:to_sym) & Groupdate::PERIODS).map(&:to_s)
  21 + if permitted_periods.include?(period.to_s)
  22 + send("group_by_#{period}", options, &block)
  23 + else
  24 + raise ArgumentError, "Unpermitted period"
  25 + end
19 26 else
20   - raise ArgumentError, "Unpermitted period"
  27 + scoping { @klass.send(:group_by_period, *args, &block) }
21 28 end
22 29 end
23 30 end
... ...
test/test_helper.rb
... ... @@ -293,6 +293,15 @@ module TestDatabase
293 293 assert_equal expected, user.posts.group_by_day(:created_at).count
294 294 end
295 295  
  296 + def test_associations_period
  297 + user = create_user("2014-03-01")
  298 + user.posts.create!(created_at: "2014-04-01 00:00:00 UTC")
  299 + expected = {
  300 + Date.parse("2014-04-01") => 1
  301 + }
  302 + assert_equal expected, user.posts.group_by_period(:day, :created_at).count
  303 + end
  304 +
296 305 # activerecord default_timezone option
297 306  
298 307 def test_default_timezone_local
... ...