class Circa::Date

Manage partial dates. @!attribute [r] valid_parts

@return [Hash]
  A hash of valid parts in the date,
  with keys [:year, :month, :day] where applicable,
  and according values

Constants

REGEX

Match partial dates in format %Y-%m-%d

Attributes

valid_parts[R]

Public Class Methods

new(date_string) click to toggle source

Create a new {Circa::Date} @param [String] date_string

A string in format %Y-%m-%d

@raise [ArgumentError]

If an invalid string is given
# File lib/circa/date.rb, line 26
def initialize(date_string)
  @year = '0000'
  @month = '00'
  @day = '00'
  @valid_parts = {}
  unless validate(date_string)
    raise ArgumentError, "Invalid date: #{date_string}"
  end
end

Public Instance Methods

to_date() click to toggle source

Get the date as a {::Date} @return [::Date]

A {::Date}
# File lib/circa/date.rb, line 46
def to_date
  return nil if valid_parts.empty?
  parts = [:year, :month, :day]
  args = valid_parts_as_args(parts)
  ::Date.send(:new, *args)
end
to_s() click to toggle source

Get the date as a string @return [String]

A string in format %Y-%m-%d
# File lib/circa/date.rb, line 39
def to_s
  "#{@year}-#{@month}-#{@day}"
end

Private Instance Methods

set_day(matches) click to toggle source
# File lib/circa/date.rb, line 75
def set_day(matches)
  @day = matches[3]
  if @day.to_i > 0
    return false unless ::Date.strptime(matches[0]).to_s == matches[0]
    @valid_parts[:day] = @day
  end
  true
end
set_dependent(a, b, name) click to toggle source
# File lib/circa/date.rb, line 71
def set_dependent(a, b, name)
  a.to_i > 0 ? @valid_parts[name] = a : b.to_i == 0
end
set_month(matches) click to toggle source
# File lib/circa/date.rb, line 66
def set_month(matches)
  @month = matches[2]
  set_dependent(@month, matches[3], :month)
end
set_year(matches) click to toggle source
# File lib/circa/date.rb, line 61
def set_year(matches)
  @year = matches[1]
  set_dependent(@year, matches[2], :year)
end
validate(date_string) click to toggle source
# File lib/circa/date.rb, line 55
def validate(date_string)
  matches = REGEX.match(date_string)
  return false if matches.nil?
  set_year(matches) && set_month(matches) && set_day(matches)
end