Sha256: 40f3fbb6d15ad03f7c24a0fed1efc7ff0ec76522936df7ee79dd8bf2a56585c4

Contents?: true

Size: 1.84 KB

Versions: 2

Compression:

Stored size: 1.84 KB

Contents

module Datewari
  class Paginator
    class Base
      class_attribute :cast_function, :date_format

      def initialize(rel, column, order, options)
        @rel = rel
        @column = column
        @order = order
        @scope = options[:scope]
      end

      def pages
        send("pages_for_#{@scope}")
      end

      def paginate(start_date, end_date)
        @rel.where("#{quoted_column} BETWEEN ? AND ?", start_date, end_date)
            .order("#{quoted_column} #{@order.to_s.upcase}")
      end

      def total_entries
        @rel.count
      end

      private

      def quoted_column
        table_column = if @column.to_s.include?('.')
                         @column
                       else
                         "#{@rel.klass.table_name}.#{@column}"
                       end
        @rel.klass.connection.quote_table_name(table_column)
      end

      def pages_for_yearly
        dates = pluck_dates(self.class.cast_function, self.class.date_format[:yearly])
        dates.map { |date| Date.parse(date) }
      end

      def pages_for_monthly
        dates = pluck_dates(self.class.cast_function, self.class.date_format[:monthly])
        dates.map { |date| Date.parse(date) }
      end

      def pages_for_weekly
        dates = pluck_dates(self.class.cast_function, self.class.date_format[:weekly])
        dates.map { |date| Date.commercial(*date.split('-').map(&:to_i)) }
      end

      def pages_for_daily
        dates = pluck_dates(self.class.cast_function, self.class.date_format[:daily])
        dates.map { |date| Date.parse(date) }
      end

      def pluck_dates(function, format)
        date_sql = "#{function}(#{quoted_column}, '#{format}')"
        @rel.limit(nil)
            .offset(nil)
            .group(date_sql)
            .reorder("#{date_sql} #{@order}")
            .pluck(date_sql)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
datewari-1.0.1 lib/datewari/paginator/base.rb
datewari-1.0.0 lib/datewari/paginator/base.rb