Sha256: b9e5d30b02cdd93d16ea8980e42965e165d87c148554b12ec9c25d79e23bb785

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

# frozen_string_literal: true

require 'json'
require 'singleton'

class Holiday
  attr_reader :calendars

  CALENDARS_FILENAME = File.expand_path(
    "#{File.dirname(__FILE__)}/../data/calendars.json"
  )

  def initialize(calendars)
    @calendars = calendars
  end

  def in(year)
    holidays[year]
  end

  def load_data
    # TODO: remove this in a major version
    holidays
    calendars
  end

  private

  def holidays
    @holidays ||= calendars.flat_map(&method(:to_holidays)).uniq.
                  reduce({}, &method(:by_year))
  end

  def by_year(holidays_by_year, date)
    holidays_by_year ||= {}
    holidays_by_year[date.year] ||= []
    holidays_by_year[date.year] << date
    holidays_by_year
  end

  def to_holidays(calendar)
    holiday_file(calendar).map(&:to_date)
  end

  def holiday_file(calendar)
    filename = holiday_filename(calendar)

    return if filename.nil?

    path = File.dirname(__FILE__) + "/../data/#{filename}"
    JSON.parse(File.read(File.expand_path(path)))
  end

  def holiday_filename(calendar)
    holiday_files.select do |_filename, calendar_names|
      calendar_names.include?(calendar)
    end.keys.first
  end

  def holiday_files
    @holiday_files ||= JSON.parse(File.read(CALENDARS_FILENAME))
    @holiday_files
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
work_day-2.0.1 lib/holiday.rb
work_day-2.0.0 lib/holiday.rb
work_day-1.3.1 lib/holiday.rb
work_day-1.3.0 lib/holiday.rb
work_day-1.2.0 lib/holiday.rb