Sha256: e380e72b075744c0456a57a23ef0b0327452966d081654401ba68404dd417139

Contents?: true

Size: 1.15 KB

Versions: 7

Compression:

Stored size: 1.15 KB

Contents

# frozen_string_literal: true

require "montrose/rule/nth_day_matcher"

module Montrose
  module Rule
    class NthDayOfMonth
      include Montrose::Rule

      def self.apply_options?(opts)
        (opts[:every] == :month || 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 month 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, MonthDay.new(time))
        expected_occurrences.any? { |n| nth_day.matches?(n) }
      end

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

        def nth_day
          @time.mday
        end

        def first_wday
          @time.beginning_of_month.wday
        end

        def total_days
          ::Montrose::Utils.days_in_month(@time.month, @time.year)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
montrose-0.12.0 lib/montrose/rule/nth_day_of_month.rb
montrose-0.11.2 lib/montrose/rule/nth_day_of_month.rb
montrose-0.11.1 lib/montrose/rule/nth_day_of_month.rb
montrose-0.11.0 lib/montrose/rule/nth_day_of_month.rb
montrose-0.10.1 lib/montrose/rule/nth_day_of_month.rb
montrose-0.10.0 lib/montrose/rule/nth_day_of_month.rb
montrose-0.9.0 lib/montrose/rule/nth_day_of_month.rb