lib/holiday.rb in work_day-1.1.0 vs lib/holiday.rb in work_day-1.2.0

- old
+ new

@@ -2,40 +2,63 @@ require 'json' require 'singleton' class Holiday - attr_reader :holidays, :calendars + 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 - @holidays = {} + # TODO: remove this in a major version + holidays + calendars + end - calendars.each do |calendar| - file = File.expand_path( - File.dirname(__FILE__) + "/../data/#{calendar}_holidays.json" - ) - raw_data = File.read(file) - parsed = JSON.parse(raw_data) - update_holidays(parsed) - end + private + + def holidays + @holidays ||= calendars.flat_map(&method(:to_holidays)).uniq. + reduce({}, &method(:by_year)) end - def in(year) - load_data if holidays.nil? - holidays[year] + 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 - private + def to_holidays(calendar) + holiday_file(calendar).map(&:to_date) + end - def update_holidays(parsed) - parsed.map do |str| - str.split('-') - date = Date.parse(str) - @holidays[date.year] ||= [] - @holidays[date.year] << 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