Sha256: 8496b9878028a7084c364651c7cde040718be6b4b49b02b6bfe4365378cc9518

Contents?: true

Size: 1.24 KB

Versions: 6

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

module Montrose
  module Rule
    class NthDayOfYear
      include Montrose::Rule

      def self.apply_options?(opts)
        opts[:every] == :year && !opts[:month] && opts[:day].is_a?(Hash)
      end

      def self.apply_options(opts)
        opts[:day]
      end

      # Initializes rule
      #
      # @param [Hash] days - valid days of week to year occurrence pairs
      #
      def initialize(days)
        @days = days
      end

      def include?(time)
        @days.key?(time.wday) && nth_day?(time)
      end

      private

      def nth_day?(time)
        expected_occurrences = @days[time.wday]
        nth_day = NthDayMatcher.new(time.wday, YearDay.new(time))
        expected_occurrences.any? { |n| nth_day.matches?(n) }
      end

      class YearDay
        def initialize(time)
          @time = time
        end

        def nth_day
          @time.yday
        end

        def first_wday
          @time.beginning_of_year.wday
        end

        def total_days
          days_in_year(@time)
        end

        private

        # Get the days in the month for +time
        def days_in_year(time)
          date = time.to_date
          ((date + 1.year) - date).to_i
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
montrose-0.18.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.17.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.16.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.15.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.14.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.13.0 lib/montrose/rule/nth_day_of_year.rb