Sha256: a4f16fc4bac448b739902eede3a3453100027a1def593003cec624d3c1531821

Contents?: true

Size: 1.35 KB

Versions: 1

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

require 'holiday'
require 'active_support'
require 'active_support/core_ext'

class WorkDay
  attr_reader :calendars

  def initialize(calendars = ['brazil'])
    @calendars = calendars
    @holidays = {}
  end

  def work_day?(date)
    date = date.try(:to_date)
    return unless date
    ![0, 6].include?(date.wday) && !holidays_in(date.year).include?(date)
  end

  def last_until(date, days = 0)
    date = date.try(:to_date)
    return unless date
    date -= 1 until work_day?(date)
    days -= 1
    days == -1 ? date : last_until(1.day.ago(date), days)
  end

  def next_after(date, days = 1)
    date = date.try(:to_date)
    day_counter = 0
    while day_counter < days
      date += 1
      day_counter += 1 if work_day?(date)
    end
    work_day?(date) ? date : next_after(date)
  end

  def between(start_date, end_date)
    (start_date.to_date..end_date.to_date).select { |date| work_day?(date) }
  end

  def self.work_day?(date)
    WorkDay.new.work_day?(date)
  end

  def self.last_until(date, days = 0)
    WorkDay.new.last_until(date, days)
  end

  def self.next_after(date, days = 1)
    WorkDay.new.next_after(date, days)
  end

  def self.between(start_date, end_date)
    WorkDay.new.between(start_date, end_date)
  end

  private

  def holidays_in(year)
    @holidays[year] ||= Holiday.new(calendars).in(year)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
work_day-1.0.0 lib/work_day.rb