Commit 948781efb439a84604d7730e6b5a14069b45a2f8
1 parent
051641f8
Exists in
master
and in
17 other branches
Accept Rails time zone strings
Showing
3 changed files
with
10 additions
and
5 deletions
Show diff stats
README.md
... | ... | @@ -40,13 +40,16 @@ Goal.group_by_year(:accomplished_at).count |
40 | 40 | The default time zone is `Time.zone`. Pass a time zone as the second argument. |
41 | 41 | |
42 | 42 | ```ruby |
43 | -time_zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"] | |
44 | -User.group_by_week(:created_at, time_zone).count | |
43 | +User.group_by_week(:created_at, "Pacific Time (US & Canada)").count | |
45 | 44 | # { |
46 | 45 | # "2013-02-25 08:00:00+00" => 80, |
47 | 46 | # "2013-03-04 08:00:00+00" => 70, |
48 | 47 | # "2013-03-11 07:00:00+00" => 54 |
49 | 48 | # } |
49 | + | |
50 | +# equivalently | |
51 | +time_zone = ActiveSupport::TimeZone["Pacific Time (US & Canada)"] | |
52 | +User.group_by_week(:created_at, time_zone).count | |
50 | 53 | ``` |
51 | 54 | |
52 | 55 | Use it with anything you can use `group` with: | ... | ... |
lib/groupdate.rb
... | ... | @@ -29,10 +29,12 @@ module Groupdate |
29 | 29 | # http://www.postgresql.org/docs/9.1/static/functions-datetime.html |
30 | 30 | %w(microseconds milliseconds second minute hour day week month quarter year decade century millennium).each do |field| |
31 | 31 | self.scope :"group_by_#{field}", lambda {|column, time_zone = Time.zone| |
32 | - if defined?(ActiveSupport::TimeZone) and time_zone.is_a?(ActiveSupport::TimeZone) | |
32 | + time_zone ||= "Etc/UTC" | |
33 | + if time_zone.is_a?(ActiveSupport::TimeZone) or time_zone = ActiveSupport::TimeZone[time_zone] | |
33 | 34 | time_zone = time_zone.tzinfo.name |
35 | + else | |
36 | + raise "Unrecognized time zone" | |
34 | 37 | end |
35 | - time_zone ||= "Etc/UTC" | |
36 | 38 | sql = "DATE_TRUNC('#{field}', #{column}::timestamptz AT TIME ZONE ?) AT TIME ZONE ?" |
37 | 39 | group(sanitize_sql_array([sql, time_zone, time_zone])) |
38 | 40 | } | ... | ... |
test/groupdate_test.rb
... | ... | @@ -45,7 +45,7 @@ class TestGroupdate < MiniTest::Unit::TestCase |
45 | 45 | "2013-03-31 07:00:00+00" => 2, |
46 | 46 | "2013-04-01 07:00:00+00" => 1 |
47 | 47 | } |
48 | - assert_equal expected, User.group_by_day(:created_at, "America/Los_Angeles").count | |
48 | + assert_equal expected, User.group_by_day(:created_at, "Pacific Time (US & Canada)").count | |
49 | 49 | end |
50 | 50 | |
51 | 51 | def test_where | ... | ... |