Class: Groupdate::Magic

Inherits:
Object
  • Object
show all
Defined in:
lib/groupdate/magic.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(field, options) ⇒ Magic

Returns a new instance of Magic.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/groupdate/magic.rb', line 5

def initialize(field, options)
  @field = field
  @options = options

  if !time_zone
    raise "Unrecognized time zone"
  end

  if field == :week and !week_start
    raise "Unrecognized :week_start option"
  end
end

Instance Attribute Details

#fieldObject

Returns the value of attribute field.



3
4
5
# File 'lib/groupdate/magic.rb', line 3

def field
  @field
end

#optionsObject

Returns the value of attribute options.



3
4
5
# File 'lib/groupdate/magic.rb', line 3

def options
  @options
end

Instance Method Details

#group_by(enum, &block) ⇒ Object



18
19
20
# File 'lib/groupdate/magic.rb', line 18

def group_by(enum, &block)
  series(enum.group_by{|v| v = yield(v); v ? round_time(v) : nil }, [])
end

#perform(relation, method, *args, &block) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/groupdate/magic.rb', line 91

def perform(relation, method, *args, &block)
  # undo reverse since we do not want this to appear in the query
  reverse = relation.reverse_order_value
  if reverse
    relation = relation.reverse_order
  end
  order = relation.order_values.first
  if order.is_a?(String)
    parts = order.split(" ")
    reverse_order = (parts.size == 2 && parts[0].to_sym == field && parts[1].to_s.downcase == "desc")
    reverse = !reverse if reverse_order
  end

  multiple_groups = relation.group_values.size > 1

  cast_method =
    case field
    when :day_of_week, :hour_of_day
      lambda{|k| k.to_i }
    else
      utc = ActiveSupport::TimeZone["UTC"]
      lambda{|k| (k.is_a?(String) ? utc.parse(k) : k.to_time).in_time_zone(time_zone) }
    end

  count =
    begin
      Hash[ relation.send(method, *args, &block).map{|k, v| [multiple_groups ? k[0...@group_index] + [cast_method.call(k[@group_index])] + k[(@group_index + 1)..-1] : cast_method.call(k), v] } ]
    rescue NoMethodError
      raise "Be sure to install time zone support - https://github.com/ankane/groupdate#for-mysql"
    end

  series(count, 0, multiple_groups, reverse)
end

#relation(column, relation) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/groupdate/magic.rb', line 22

def relation(column, relation)
  column = relation.connection.quote_table_name(column)
  time_zone = self.time_zone.tzinfo.name

  adapter_name = relation.connection.adapter_name
  query =
    case adapter_name
    when "MySQL", "Mysql2"
      case field
      when :day_of_week # Sunday = 0, Monday = 1, etc
        # use CONCAT for consistent return type (String)
        ["DAYOFWEEK(CONVERT_TZ(DATE_SUB(#{column}, INTERVAL #{day_start} HOUR), '+00:00', ?)) - 1", time_zone]
      when :hour_of_day
        ["(EXTRACT(HOUR from CONVERT_TZ(#{column}, '+00:00', ?)) + 24 - #{day_start}) % 24", time_zone]
      when :week
        ["CONVERT_TZ(DATE_FORMAT(CONVERT_TZ(DATE_SUB(#{column}, INTERVAL ((#{7 - week_start} + WEEKDAY(CONVERT_TZ(#{column}, '+00:00', ?) - INTERVAL #{day_start} HOUR)) % 7) DAY) - INTERVAL #{day_start} HOUR, '+00:00', ?), '%Y-%m-%d 00:00:00') + INTERVAL #{day_start} HOUR, ?, '+00:00')", time_zone, time_zone, time_zone]
      else
        format =
          case field
          when :second
            "%Y-%m-%d %H:%i:%S"
          when :minute
            "%Y-%m-%d %H:%i:00"
          when :hour
            "%Y-%m-%d %H:00:00"
          when :day
            "%Y-%m-%d 00:00:00"
          when :month
            "%Y-%m-01 00:00:00"
          else # year
            "%Y-01-01 00:00:00"
          end

        ["DATE_ADD(CONVERT_TZ(DATE_FORMAT(CONVERT_TZ(DATE_SUB(#{column}, INTERVAL #{day_start} HOUR), '+00:00', ?), '#{format}'), ?, '+00:00'), INTERVAL #{day_start} HOUR)", time_zone, time_zone]
      end
    when "PostgreSQL", "PostGIS"
      case field
      when :day_of_week
        ["EXTRACT(DOW from (#{column}::timestamptz AT TIME ZONE ? - INTERVAL '#{day_start} hour'))::integer", time_zone]
      when :hour_of_day
        ["EXTRACT(HOUR from #{column}::timestamptz AT TIME ZONE ? - INTERVAL '#{day_start} hour')::integer", time_zone]
      when :week # start on Sunday, not PostgreSQL default Monday
        ["(DATE_TRUNC('#{field}', (#{column}::timestamptz - INTERVAL '#{week_start} day' - INTERVAL '#{day_start}' hour) AT TIME ZONE ?) + INTERVAL '#{week_start} day' + INTERVAL '#{day_start}' hour) AT TIME ZONE ?", time_zone, time_zone]
      else
        ["(DATE_TRUNC('#{field}', (#{column}::timestamptz - INTERVAL '#{day_start} hour') AT TIME ZONE ?) + INTERVAL '#{day_start} hour') AT TIME ZONE ?", time_zone, time_zone]
      end
    else
      raise "Connection adapter not supported: #{adapter_name}"
    end

  group = relation.group(Groupdate::OrderHack.new(relation.send(:sanitize_sql_array, query), field, time_zone))
  if options[:series] == false
    group
  else
    relation =
      if time_range.is_a?(Range)
        # doesn't matter whether we include the end of a ... range - it will be excluded later
        group.where("#{column} >= ? AND #{column} <= ?", time_range.first, time_range.last)
      else
        group.where("#{column} IS NOT NULL")
      end

    # TODO do not change object state
    @group_index = group.group_values.size - 1

    Groupdate::Series.new(self, relation)
  end
end