Class: ParseDate

Inherits:
Object
  • Object
show all
Extended by:
IntFromString
Includes:
Singleton
Defined in:
lib/parse_date.rb,
lib/parse_date/version.rb,
lib/parse_date/int_from_string.rb

Defined Under Namespace

Modules: IntFromString Classes: Error

Constant Summary collapse

VERSION =
'0.4.4'

Class Method Summary collapse

Methods included from IntFromString

earliest_year, latest_year, year_int_valid?

Class Method Details

.parse_range(date_str) ⇒ Array

Returns array of Integer year values from earliest year to latest year, inclusive.

Returns:

  • (Array)

    array of Integer year values from earliest year to latest year, inclusive



29
30
31
32
33
34
35
36
37
38
# File 'lib/parse_date.rb', line 29

def self.parse_range(date_str)
  first = earliest_year(date_str)
  last = latest_year(date_str)
  return nil unless first || last
  raise Error, "Unable to parse range from '#{date_str}'" unless year_range_valid?(first, last)

  range_array(first, last)
rescue StandardError => e
  raise Error, "Unable to parse range from '#{date_str}': #{e.message}"
end

.range_array(first_year, last_year) ⇒ Array

Returns array of Integer year values from first to last, inclusive.

Parameters:

  • first_year, (Integer, String)

    expecting integer or parseable string for .to_i

  • last_year, (Integer, String)

    expecting integer or parseable string for .to_i

Returns:

  • (Array)

    array of Integer year values from first to last, inclusive

Raises:



55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/parse_date.rb', line 55

def self.range_array(first_year, last_year) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  first_year = first_year.to_i if first_year.is_a?(String) && first_year.match?(/^-?\d+$/)
  last_year = last_year.to_i if last_year.is_a?(String) && last_year.match?(/^-?\d+$/)

  return [] unless last_year || first_year
  return [first_year] if last_year.nil? && first_year
  return [last_year] if first_year.nil? && last_year
  raise(Error, "unable to create year range array from #{first_year}, #{last_year}") unless
    year_range_valid?(first_year, last_year)

  Range.new(first_year, last_year).to_a
end

.year_range_valid?(first_year, last_year) ⇒ Boolean

true if:

both years are not newer than (current year + 1)
first_year <= last_year

false otherwise

Returns:

  • (Boolean)


44
45
46
47
48
49
50
# File 'lib/parse_date.rb', line 44

def self.year_range_valid?(first_year, last_year)
  upper_bound = Date.today.year + 2
  return false if first_year > upper_bound || last_year > upper_bound
  return false if first_year > last_year

  true
end