Module: WhatDate::DateOfMonth

Included in:
Client
Defined in:
lib/what_date/date_of_month.rb

Constant Summary collapse

ORDINALS =
{ "first" => 1, "second" => 2, "third" => 3, "fourth" => 4, "fifth" => 5, "last" => nil }.freeze
ORDERS =
'first||second||third||fourth||fifth||last'.freeze
WEEKDAYS =
'monday||tuesday||wednesday||thursday||friday||saturday||sunday'.freeze
MONTHS =
'january||february||march||april||may||june||july||august||september||october||november||december'.freeze

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/what_date/date_of_month.rb', line 27

def method_missing(name, *args, &block)
	methods = missing_method_reg.match(name)
	if methods 
		order = ORDINALS[methods[1].downcase]
		day = format_date_string methods[2]
		month = format_date_string methods[3]
		year = methods[4] ? methods[4][/\d+/].to_i : Date.today.year
		order == nil ? date_of_last_week_day_in_month(day, month, year) :
		               date_of_month(order: order, day: day, month: month, year: year)
	else
		super
	end
end

Instance Method Details

#date_of_month(order: 1, day:, month:, year: Date.today.year) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/what_date/date_of_month.rb', line 10

def date_of_month(order:1, day:, month:, year: Date.today.year)
	month_int = Date::MONTHNAMES.index(month)
	first_date = Date.new(year, month_int, 1)
	first_day = first_date.wday
	lookup = Date::DAYNAMES.index(day.titleize)
	if lookup < first_day
		inc = (order - 1) * 7 + (lookup - first_day + 8)
	else
		inc = (order - 1) * 7 + (lookup - first_day +  1)
	end
	begin
		Date.new(year, month_int, inc)
	rescue ArgumentError
		nil
	end
end

#last_date_of_month(month:, year:) ⇒ Object



41
42
43
44
45
46
47
# File 'lib/what_date/date_of_month.rb', line 41

def last_date_of_month(month:, year:)
	begin
		Date.parse("#{year}-#{month}-1").end_of_month
	rescue ArgumentError
		nil
	end
end