Class: ActiveSupport::Duration

Inherits:
Object
  • Object
show all
Defined in:
lib/active_support/duration/human_string.rb,
lib/active_support/duration/human_string.rb,
lib/active_support/duration/human_string/version.rb

Defined Under Namespace

Modules: HumanString Classes: HumanStringSerializer

Instance Method Summary collapse

Instance Method Details

#human_str(precision: nil, separator: '', delimiter: ' ', use_2_digit_numbers: false) ⇒ Object Also known as: human_string, to_human_s

Convert ActiveSupport::Duration objects to human-friendly strings like '2h 30m 17s' or '3y 6m 4d 12h 30m 5s'.

Note that the unit 'm' is used for both months and minutes.

Examples

duration = 3500.seconds
duration.human_str                 # =>  '58m 20s'
duration.human_str(delimiter: '')  # =>  '58m20s'
duration.human_str(separator: ' ') # =>  '58 m 20 s'
duration.human_str(delimiter: ', ', separator: ' ') # =>  '58 m, 20 s'

duration = ActiveSupport::Duration.parse "P3Y6M4DT12H30M5S"
# => 3 years, 6 months, 4 days, 12 hours, 30 minutes, and 5 seconds

duration.human_str                  # => "3y 6m 4d 12h 30m 5s"
(duration - 4.days).human_str       # => "3y 6m 12h 30m 5s"
duration.human_str(delimiter: ', ') # => "3y, 6m, 4d, 12h, 30m, 5s"

Options

:precision: Precision of seconds (defaults to nil, which is no digits after decimal).

:separator: The separator between the digits and units (defaults to '', giving for example '3h' with nothing between them).

:delimiter: The delimiter between different parts like minutes and seconds (defaults to ' ').

use_2_digit_numbers: Set to true if you want to pad 1-digit nubers to 2 digits ('3h 05m 07s' instead of '3h 5m 7s'). Never pads the first part of the duration, only later parts.



44
45
46
47
48
49
50
51
52
# File 'lib/active_support/duration/human_string.rb', line 44

def human_str(precision: nil, separator: '', delimiter: ' ', use_2_digit_numbers: false)
  HumanStringSerializer.new(
    self.class.build(value),
    precision: precision,
    separator: separator,
    delimiter: delimiter,
    use_2_digit_numbers: use_2_digit_numbers,
  ).serialize
end