Class: StructuredStore::Converters::ChronicDateRangeConverter

Inherits:
Object
  • Object
show all
Defined in:
lib/structured_store/converters/chronic_date_range_converter.rb

Overview

This class is responsible for converting date ranges to and from a string format.

Instance Method Summary collapse

Instance Method Details

#convert_to_dates(value) ⇒ Array<Time>

Converts a natural language date range string into an array containing start and end dates

Parameters:

  • value (String)

    A natural language date range string (e.g., “between 1st and 15th January 2024”)

Returns:

  • (Array<Time>)

    An array containing two Time objects: [start_date, end_date]

Raises:

  • (NoMethodError)

    If the input string cannot be parsed into a valid date range



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/structured_store/converters/chronic_date_range_converter.rb', line 14

def convert_to_dates(value)
  return [nil, nil] if value.blank?

  if /\A\d{4}\z/.match?(value.strip)
    # If the value is a year, return the start and end of that year
    year = value.strip.to_i
    return [Time.new(year, 1, 1), Time.new(year, 12, 31)]
  end

  parsed_date_range = Chronic.parse(value, endian_precedence: :little, guess: false)

  [parsed_date_range&.begin, parsed_date_range&.end&.days_ago(1)]
end

#convert_to_string(date1, date2) ⇒ String

Formats two dates into a human readable date range string

Examples:

convert_to_string(Date.new(2023,1,1), Date.new(2023,1,1)) #=> "1 Jan 2023"
convert_to_string(Date.new(2023,1,1), Date.new(2023,1,31)) #=> "Jan 2023"
convert_to_string(Date.new(2023,1,1), Date.new(2023,12,31)) #=> "2023"
convert_to_string(Date.new(2023,1,1), Date.new(2023,2,1)) #=> "1 Jan 2023 to 1 Feb 2023"

Parameters:

  • date1 (Date)

    The start date of the range

  • date2 (Date)

    The end date of the range

Returns:

  • (String)

    A formatted date range string in one of these formats:

    • “D MMM YYYY” (when dates are equal)

    • “MMM YYYY” (when dates span a full month in the same year)

    • “YYYY” (when dates span a full year)

    • “D MMM YYYY to D MMM YYYY” (for all other date ranges)



42
43
44
45
46
47
48
# File 'lib/structured_store/converters/chronic_date_range_converter.rb', line 42

def convert_to_string(date1, date2)
  return format_single_date(date1) if date1 == date2
  return format_full_month(date1) if full_month_range?(date1, date2)
  return format_full_year(date1) if full_year_range?(date1, date2)

  format_date_range(date1, date2)
end