Sha256: 52f6df8a85f9cbcc84063f98589dd1a516ccd2a1e19fb61383ee397433e92669

Contents?: true

Size: 955 Bytes

Versions: 1

Compression:

Stored size: 955 Bytes

Contents

module SlideRule
  module DistanceCalculators
    class DayOfMonth
      MAX_DAYS = 15

      #
      # Calculates distance using 15 as the max point.
      #   Does not take into account the number of days in the actual month being considered.
      #
      def calculate(first, second)
        return nil if first.nil? || second.nil?
        first = cleanse_date(first)
        second = cleanse_date(second)

        difference_in_days(first, second).to_f / MAX_DAYS
      end

      def difference_in_days(first, second)
        distance = (first.mday - second.mday).abs
        return distance if distance <= MAX_DAYS
        MAX_DAYS - (distance - MAX_DAYS)
      end

      private

      def cleanse_date(date)
        date = Time.at(date).utc.to_date if date.is_a?(::Fixnum)
        date = Date.parse(date) unless date.is_a?(::Date) || date.is_a?(::Time)
        date = date.to_date if date.is_a?(::Time)

        date
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
slide_rule-0.2.2 lib/slide_rule/distance_calculators/day_of_month.rb