Class: ActiveDateRange::Humanizer

Inherits:
Object
  • Object
show all
Defined in:
lib/active_date_range/humanizer.rb

Overview

Translates a DateRange to a human readable format. Localization and translations are handled by I18n.

Valid format parameters:

  • short (default): Jan 1, 2021 - Jan 15, 2021

  • long: January 12, 2021 - January 15, 2021

  • relative: when available, returns a relative translation like “this month” or “next year”.

  • explicit: never shortens a short or long format (see below)

Unless you use the :explicit format, the translation is as short as possible:

DateRange.parse("20210101..20210101").humanize # => "Jan 1, 2021"
DateRange.parse("20210101..20210115").humanize # => "Jan 1 - Jan 15, 2021"
DateRange.parse("20210101..20220115").humanize # => "Jan 1 2021 - Jan 15, 2022"
DateRange.parse("202101..202101").humanize # => "Jan 2021"
DateRange.parse("202101..202102").humanize # => "Jan - Feb 2021"
DateRange.parse("202101..202202").humanize # => "Jan 2021 - Feb 2022"
DateRange.parse("202101..202103").humanize # => "Q1 2021"
DateRange.parse("202101..202106").humanize # => "Q1 - Q2 2021"
DateRange.parse("202101..202206").humanize # => "Q1 2021 - Q2 2022"
DateRange.parse("202101..202112").humanize # => "2021"
DateRange.parse("202101..202212").humanize # => "2021 - 2021"

Translations and formats are completely customizable through I18n, see locales/en.yml for an overview of translatable keys.

Constant Summary collapse

FORMATS =
%i[short long relative explicit]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(date_range, format: :short) ⇒ Humanizer

Returns a new instance of Humanizer.

Raises:

  • (ArgumentError)


36
37
38
39
40
41
# File 'lib/active_date_range/humanizer.rb', line 36

def initialize(date_range, format: :short)
  @date_range = date_range
  raise ArgumentError, "Unknown format #{format} for humanize, valid formats: #{FORMATS.join(", ")}" unless FORMATS.include?(format)

  @format = format
end

Instance Attribute Details

#date_rangeObject (readonly)

Returns the value of attribute date_range.



32
33
34
# File 'lib/active_date_range/humanizer.rb', line 32

def date_range
  @date_range
end

#formatObject (readonly)

Returns the value of attribute format.



32
33
34
# File 'lib/active_date_range/humanizer.rb', line 32

def format
  @format
end

Instance Method Details

#humanizeObject



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/active_date_range/humanizer.rb', line 43

def humanize
  return day_range if format == :explicit

  if format == :relative
    return relative if date_range.relative_param

    @format = :short
  end

  one_day || year || quarter || month || day_range
end