Class: GoogleHolidayCalendar::Calendar

Inherits:
Object
  • Object
show all
Defined in:
lib/google_holiday_calendar/calendar.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(country: "usa", lang: "en", api_key: nil) ⇒ Calendar

Returns a new instance of Calendar.

Parameters:

  • country (String) (defaults to: "usa")
  • lang (String) (defaults to: "en")


10
11
12
13
14
# File 'lib/google_holiday_calendar/calendar.rb', line 10

def initialize(country: "usa", lang: "en", api_key: nil)
  @country = country.downcase
  @lang    = lang.downcase
  @api_key = api_key
end

Instance Attribute Details

#countryObject (readonly)

Returns the value of attribute country.



6
7
8
# File 'lib/google_holiday_calendar/calendar.rb', line 6

def country
  @country
end

#langObject (readonly)

Returns the value of attribute lang.



6
7
8
# File 'lib/google_holiday_calendar/calendar.rb', line 6

def lang
  @lang
end

Instance Method Details

#holiday?(arg) ⇒ Boolean

whether arg is holiday

Parameters:

  • arg (#to_date, String)

    Date, Time, or date like String (ex. "YYYY-MM-DD")

Returns:

  • (Boolean)


53
54
55
56
# File 'lib/google_holiday_calendar/calendar.rb', line 53

def holiday?(arg)
  date = to_date(arg)
  holidays(start_date: date, end_date: date + 1.day, limit: 1).length > 0
end

#holidays(start_date: nil, end_date: nil, limit: 10) ⇒ Hash, {}

get holidays via google calendar

Parameters:

  • start_date (String, Date) (defaults to: nil)

    start date ("YYYY-MM-DD" or Date). default: current date

  • end_date (String, Date) (defaults to: nil)

    end date ("YYYY-MM-DD" or Date). not contain this date. default: 1 month after the start_date

  • limit (Integer) (defaults to: 10)

Returns:

  • (Hash)

    key: date, value: holiday title

  • ({})

    if found no holidays, return empty hash



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/google_holiday_calendar/calendar.rb', line 22

def holidays(start_date: nil, end_date: nil, limit: 10)
  start_date = Date.today unless start_date
  end_date = to_date(start_date) + 1.month unless end_date

  calendar_id = "#{@lang}.#{@country}#[email protected]"
  url = "https://www.googleapis.com/calendar/v3/calendars/#{CGI.escape(calendar_id)}/events?"
  params = {
    "key"         => @api_key,
    "timeMin"     => to_ymd(start_date),
    "timeMax"     => to_ymd(end_date),
    "maxResults" => limit,
  }
  url += params.to_query

  calendar_response = fetch(url)

  entries = calendar_response["items"]
  return {} unless entries

  holidays = entries.inject({}){ |res, item|
    date = Date.parse(item['start']['date'])
    title = item["summary"]
    res[date] =title
    res
  }

  Hash[holidays.sort_by{|k,v| k }]
end