Sha256: 2b919d947aed2a01082c26cef760b3bda20578ee118abe2e804e028314c69378

Contents?: true

Size: 1.13 KB

Versions: 55

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

module CoreExtensions
  module ActiveSupport
    module DurationAdditions
      FORMATTING_ELEMENTS = [:years, :months, :weeks, :days, :hours, :minutes, :seconds].freeze

      # Add a custom method on ActiveSupportDuration.
      # This is a variation on Duration#inspect that excludes empty parts.
      # Given an iso8601 duration of 1 week:
      #   duration = Duration.parse("P1W")
      #   duration.inspect        #=> "1 week, 0 days, and 0 hours"
      #   duration.to_formatted_s #=> "1 week"
      #
      # rubocop:disable Style/Semicolon, Style/EachWithObject, Metrics/AbcSize
      def to_formatted_s
        parts
          .reduce(::Hash.new(0)) { |h, (l, r)| h[l] += r; h }
          .reject{ |_, val| val < 1 }
          .sort_by { |unit, _| FORMATTING_ELEMENTS.index(unit) }
          .map { |unit, val| "#{val} #{val == 1 ? unit.to_s.chop : unit.to_s}" }
          .to_sentence(locale: ::I18n.default_locale)
      end
      # rubocop:enable Style/Semicolon, Style/EachWithObject, Metrics/AbcSize
    end
  end
end

ActiveSupport::Duration.send(:include, CoreExtensions::ActiveSupport::DurationAdditions)

Version data entries

55 entries across 55 versions & 1 rubygems

Version Path
renalware-core-2.0.77 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.76 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.75 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.74 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.73 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.72 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.71 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.70 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.69 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.68 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.67 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.64 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.63 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.62 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.61 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.60 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.58 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.57 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.56 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.55 lib/core_extensions/active_support/duration.rb