Sha256: 78635294e0d1fb9dcfd11bd83d970112689204fe9a723a041c368612af524cd2

Contents?: true

Size: 1.23 KB

Versions: 12

Compression:

Stored size: 1.23 KB

Contents

require "montrose/rule/nth_day_matcher"

module Montrose
  module Rule
    class NthDayOfYear
      include Montrose::Rule

      def self.apply_options?(opts)
        opts[:every] == :year && 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

12 entries across 12 versions & 1 rubygems

Version Path
montrose-0.6.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.5.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.4.3 lib/montrose/rule/nth_day_of_year.rb
montrose-0.4.2 lib/montrose/rule/nth_day_of_year.rb
montrose-0.4.1 lib/montrose/rule/nth_day_of_year.rb
montrose-0.4.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.3.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.2.2 lib/montrose/rule/nth_day_of_year.rb
montrose-0.2.1 lib/montrose/rule/nth_day_of_year.rb
montrose-0.2.0 lib/montrose/rule/nth_day_of_year.rb
montrose-0.1.1 lib/montrose/rule/nth_day_of_year.rb
montrose-0.1.0 lib/montrose/rule/nth_day_of_year.rb