Sha256: e6bcfad3cf46375f5492367b729bf5407c2cde73db159c6a9bdf2ae39f77ddab

Contents?: true

Size: 1.09 KB

Versions: 54

Compression:

Stored size: 1.09 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
      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
    end
  end
end

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

Version data entries

54 entries across 54 versions & 1 rubygems

Version Path
renalware-core-2.1.1 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.1.0 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.167 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.166 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.165 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.164 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.163 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.162 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.161 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.160 lib/core_extensions/active_support/duration_additions.rb
renalware-core-2.0.159 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.158 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.157 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.156 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.155 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.153 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.152 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.151 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.149 lib/core_extensions/active_support/duration.rb
renalware-core-2.0.148 lib/core_extensions/active_support/duration.rb