Class: Groupdate::Series
- Inherits:
-
Object
- Object
- Groupdate::Series
- Defined in:
- lib/groupdate/series.rb
Instance Method Summary collapse
- #build_series(count) ⇒ Object
-
#initialize(relation, field, column, time_zone, time_range) ⇒ Series
constructor
A new instance of Series.
- #method_missing(method, *args, &block) ⇒ Object
Constructor Details
#initialize(relation, field, column, time_zone, time_range) ⇒ Series
Returns a new instance of Series.
4 5 6 7 8 9 10 11 12 |
# File 'lib/groupdate/series.rb', line 4 def initialize(relation, field, column, time_zone, time_range) @relation = relation if time_range.is_a?(Range) @relation = relation.where("#{column} BETWEEN ? AND ?", time_range.first, time_range.last) end @field = field @time_zone = time_zone @time_range = time_range end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method, *args, &block) ⇒ Object
82 83 84 85 86 87 88 89 |
# File 'lib/groupdate/series.rb', line 82 def method_missing(method, *args, &block) # https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/calculations.rb if ActiveRecord::Calculations.method_defined?(method) build_series(@relation.send(method, *args, &block)) else raise NoMethodError, "valid methods are: #{ActiveRecord::Calculations.instance_methods.join(", ")}" end end |
Instance Method Details
#build_series(count) ⇒ Object
14 15 16 17 18 19 20 21 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 |
# File 'lib/groupdate/series.rb', line 14 def build_series(count) utc = ActiveSupport::TimeZone["UTC"] cast_method = case @field when "day_of_week", "hour_of_day" lambda{|k| k.to_i } else lambda{|k| (k.is_a?(Time) ? k : utc.parse(k)).utc } end count = Hash[count.map do |k, v| [cast_method.call(k), v] end] series = case @field when "day_of_week" 0..6 when "hour_of_day" 0..23 else time_range = if @time_range.is_a?(Range) @time_range else # use first and last values sorted_keys = count.keys.sort sorted_keys.first..sorted_keys.last end # determine start time time = time_range.first.in_time_zone(@time_zone) starts_at = case @field when "second" time.change(:usec => 0) when "minute" time.change(:sec => 0) when "hour" time.change(:min => 0) when "day" time.beginning_of_day when "week" # beginning_of_week does not support :sunday argument in activesupport < 3.2 (time - time.wday.days).midnight when "month" time.beginning_of_month else # year time.beginning_of_year end series = [starts_at] step = 1.send(@field) while time_range.cover?(series.last + step) series << series.last + step end series.map{|s| s.to_time.utc } end Hash[series.map do |k| [k, count[k] || 0] end] end |