Module: DurationInWords::Methods

Extended by:
Methods
Included in:
ActionView::Helpers::DurationHelper, Methods
Defined in:
lib/duration_in_words/methods.rb,
sig/duration_in_words.rbs

Constant Summary collapse

VALID_FORMATS =

Returns:

  • (Array[Symbol])
%i[compact full].freeze

Instance Method Summary collapse

Instance Method Details

#duration_in_words(duration, options = {}) ⇒ String

Parameters:

  • duration (Object)
  • options (Hash[Symbol, untyped]) (defaults to: {})

Returns:

  • (String)


9
10
11
12
13
14
15
16
17
18
# File 'lib/duration_in_words/methods.rb', line 9

def duration_in_words(duration, options = {})
  raise_type_error(duration) unless duration.is_a?(ActiveSupport::Duration)

  locale, scope = parse_options(options)
  parts = duration.parts

  return I18n.t(:seconds, count: duration.value, scope: scope, locale: locale) if parts.empty?

  sentencify(parts, scope, locale)
end

#normalize_format(format) ⇒ Symbol

Parameters:

  • format (Object)

Returns:

  • (Symbol)

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
# File 'lib/duration_in_words/methods.rb', line 31

def normalize_format(format)
  symbol = format.respond_to?(:to_sym) ? format.to_sym : format

  return symbol if VALID_FORMATS.include?(symbol)

  raise ArgumentError,
        "invalid :format, #{format.inspect} given. Valid formats: #{VALID_FORMATS.map(&:inspect).join(', ')}"
end

#parse_options(options) ⇒ [untyped, Symbol]

Parameters:

  • options (Hash[Symbol, untyped])

Returns:

  • ([untyped, Symbol])


22
23
24
25
26
27
28
29
# File 'lib/duration_in_words/methods.rb', line 22

def parse_options(options)
  format = normalize_format(options.fetch(:format, :compact))
  locale = options.fetch(:locale, I18n.locale)

  scope = format == :full ? I18N_SCOPE_FULL : DEFAULT_I18N_SCOPE

  [locale, scope]
end

#raise_type_error(type) ⇒ bot

Parameters:

  • type (Object)

Returns:

  • (bot)

Raises:

  • (TypeError)


51
52
53
# File 'lib/duration_in_words/methods.rb', line 51

def raise_type_error(type)
  raise TypeError, "no implicit conversion of #{type.class} into ActiveSupport::Duration"
end

#sentence_options(scope, locale) ⇒ Object

Parameters:

  • scope (Symbol)
  • locale (Object)

Returns:

  • (Object)


47
48
49
# File 'lib/duration_in_words/methods.rb', line 47

def sentence_options(scope, locale)
  I18n.t(:support, scope: scope, locale: locale, default: { locale: locale })
end

#sentencify(parts, scope, locale) ⇒ String

Parameters:

  • parts (Hash[Symbol, untyped])
  • scope (Symbol)
  • locale (Object)

Returns:

  • (String)


40
41
42
43
44
45
# File 'lib/duration_in_words/methods.rb', line 40

def sentencify(parts, scope, locale)
  parts
    .sort_by { |unit, _| ActiveSupport::Duration::PARTS.index(unit) }
    .map     { |unit, val| I18n.t(unit, count: val, scope: scope, locale: locale) }
    .to_sentence(sentence_options(scope, locale))
end