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 =
%i[compact full].freeze
Instance Method Summary collapse
- #duration_in_words(duration, options = {}) ⇒ String
- #normalize_format(format) ⇒ Symbol
- #parse_options(options) ⇒ [untyped, Symbol]
- #raise_type_error(type) ⇒ bot
- #sentence_options(scope, locale) ⇒ Object
- #sentencify(parts, scope, locale) ⇒ String
Instance Method Details
#duration_in_words(duration, options = {}) ⇒ 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, = {}) raise_type_error(duration) unless duration.is_a?(ActiveSupport::Duration) locale, scope = () 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
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]
22 23 24 25 26 27 28 29 |
# File 'lib/duration_in_words/methods.rb', line 22 def () format = normalize_format(.fetch(:format, :compact)) locale = .fetch(:locale, I18n.locale) scope = format == :full ? I18N_SCOPE_FULL : DEFAULT_I18N_SCOPE [locale, scope] end |
#raise_type_error(type) ⇒ bot
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
47 48 49 |
# File 'lib/duration_in_words/methods.rb', line 47 def (scope, locale) I18n.t(:support, scope: scope, locale: locale, default: { locale: locale }) end |
#sentencify(parts, scope, locale) ⇒ 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((scope, locale)) end |