Sha256: 1f8a8671d6e6a31c00d4760e203f560fc1c6ad9ab0de5c744b302be78ed55cdd

Contents?: true

Size: 1.49 KB

Versions: 1

Compression:

Stored size: 1.49 KB

Contents

require "groupdate/version"

module Groupdate
  extend ActiveSupport::Concern

  # Pattern from kaminari
  # https://github.com/amatsuda/kaminari/blob/master/lib/kaminari/models/active_record_extension.rb
  included do
    # Future subclasses will pick up the model extension
    class << self
      def inherited_with_groupdate(kls) #:nodoc:
        inherited_without_groupdate kls
        kls.send(:include, ClassMethods) if kls.superclass == ActiveRecord::Base
      end
      alias_method_chain :inherited, :groupdate
    end

    # Existing subclasses pick up the model extension as well
    self.descendants.each do |kls|
      kls.send(:include, ClassMethods) if kls.superclass == ActiveRecord::Base
    end
  end

  module ClassMethods
    extend ActiveSupport::Concern

    included do
      # Field list from
      # http://www.postgresql.org/docs/9.1/static/functions-datetime.html
      %w(microseconds milliseconds second minute hour day week month quarter year decade century millennium).each do |field|
        self.scope :"group_by_#{field}", lambda {|column, time_zone = Time.zone|
          if defined?(ActiveSupport::TimeZone) and time_zone.is_a?(ActiveSupport::TimeZone)
            time_zone = time_zone.tzinfo.name
          end
          time_zone ||= "Etc/UTC"
          sql = "DATE_TRUNC('#{field}', #{column}::timestamptz AT TIME ZONE ?) AT TIME ZONE ?"
          group(sanitize_sql_array([sql, time_zone, time_zone]))
        }
      end
    end
  end

end

ActiveRecord::Base.send :include, Groupdate

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
groupdate-0.0.2 lib/groupdate.rb