Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
articular / lib / articular / archiver.rb
Size: Mime:
require 'articular/archive_month'

module Articular
  module Archiver
    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def archiver_field
        :published_at
      end

      def from_archive(year = nil, month = nil)
        return all if year.nil?
        return by_year(year) if month.nil?

        by_month(year, month)
      end

      def by_month(year, month)
        begin
          year = Integer(year)
          month = Integer(month)
          starts = Date.new(year, month).beginning_of_month
          ends   = Date.new(year, month).end_of_month
        rescue ArgumentError, TypeError
          raise Articular::DateError
        end

        published_between(starts, ends)
      end

      def by_year(year)
        begin
          year = Integer(year)
          starts = Date.new(year).beginning_of_year
          ends   = Date.new(year).end_of_year
        rescue ArgumentError, TypeError
          raise Articular::DateError
        end

        published_between(starts, ends)
      end

      def published_between(start_date, end_date)
        where("#{archiver_field} >= ?", start_date)
          .where("#{archiver_field} <= ?", end_date)
      end

      def archive_months
        select("date_trunc('month', #{archiver_field}) as date, count(*) as count")
          .reorder('date').group('date')
          .distinct
          .map { |row| ArchiveMonth.new(date: row.date, count: row.count) }
      end
    end
  end
end