Class: DateValues::MonthDay

Inherits:
Data
  • Object
show all
Includes:
Comparable
Defined in:
lib/date_values/month_day.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(month:, day:) ⇒ MonthDay

Returns a new instance of MonthDay.

Raises:

  • (ArgumentError)


9
10
11
12
13
14
# File 'lib/date_values/month_day.rb', line 9

def initialize(month:, day:)
  raise ArgumentError, "invalid month: #{month}" unless (1..12).include?(month)
  raise ArgumentError, "invalid day: #{day} for month: #{month}" unless (1..max_day(month)).include?(day)

  super
end

Instance Attribute Details

#dayObject (readonly)

Returns the value of attribute day

Returns:

  • (Object)

    the current value of day



6
7
8
# File 'lib/date_values/month_day.rb', line 6

def day
  @day
end

#monthObject (readonly)

Returns the value of attribute month

Returns:

  • (Object)

    the current value of month



6
7
8
# File 'lib/date_values/month_day.rb', line 6

def month
  @month
end

Class Method Details

.from(date) ⇒ Object



16
17
18
# File 'lib/date_values/month_day.rb', line 16

def self.from(date)
  new(date.month, date.day)
end

.parse(str) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/date_values/month_day.rb', line 20

def self.parse(str)
  case str
  when /\A--(\d{1,2})-(\d{1,2})\z/
    new($1.to_i, $2.to_i)
  when /\A(\d{1,2})[\/\-](\d{1,2})\z/
    a, b = $1.to_i, $2.to_i

    if DateValues.config.month_day_order == :day_first
      new(b, a)
    else
      new(a, b)
    end
  else
    raise ArgumentError, "invalid MonthDay: #{str}"
  end
end

Instance Method Details

#<=>(other) ⇒ Object



37
38
39
40
41
# File 'lib/date_values/month_day.rb', line 37

def <=>(other)
  return nil unless other.is_a?(MonthDay)

  [month, day] <=> [other.month, other.day]
end

#as_jsonObject



56
57
58
# File 'lib/date_values/month_day.rb', line 56

def as_json(*)
  to_s
end

#change(month: self.month, day: self.day) ⇒ Object



43
44
45
# File 'lib/date_values/month_day.rb', line 43

def change(month: self.month, day: self.day)
  self.class.new(month, day)
end

#inspectObject



64
65
66
# File 'lib/date_values/month_day.rb', line 64

def inspect
  "#<DateValues::MonthDay #{self}>"
end

#strftime(format) ⇒ Object



47
48
49
50
# File 'lib/date_values/month_day.rb', line 47

def strftime(format)
  # 2000 is a leap year, so Feb 29 works
  Date.new(2000, month, day).strftime(format)
end

#to_date(year) ⇒ Object



52
53
54
# File 'lib/date_values/month_day.rb', line 52

def to_date(year)
  Date.new(year, month, day)
end

#to_sObject



60
61
62
# File 'lib/date_values/month_day.rb', line 60

def to_s
  format('--%02d-%02d', month, day)
end