1
duration_to_sec("3m") => 180

Perhaps something similar to https://gist.github.com/tim-evans/d0ba1e8f05a55b76c49c but wrapped as a nice gem, or even better an internal function to do this.

Edit: I can't use ActiveRecord; also, not looking for an implementation to drop in. I already wrote one. Just looking for a gem that might have already implemented this functionality. Thanks!

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
MaxVT
  • 12,989
  • 6
  • 36
  • 50
  • See strptime - you can define your own parser https://ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/DateTime.html#method-c-strptime – max pleaner Oct 20 '16 at 21:25

2 Answers2

2

Take a look at fugit and chronic_duration, both can do the job.

fugit seems to be more maintained, not many use it directly but it's a dependency of some popular gems.

chronic_duration on the other hand is more known by itself but doesn't seem to be maintained. It's also more simple.

I'm currently using chronic_duration:

> ChronicDuration.parse '1m'
 => 60
> ChronicDuration.parse '1m60s'
 => 120
thisismydesign
  • 21,553
  • 9
  • 123
  • 126
  • These are cool and powerful, no doubt, but If I were the OP, I'd go with the bundled/copied implementation, which is very small and does what I need (and nothing else). Gems becoming abandoned is why. – Sergio Tulentsev Jan 22 '19 at 13:29
  • 1
    Well OP despite being aware of the gist and also writing his own implementation asked specifically for a gem. Besides, that gist doesn't have tests. If it would, I would agree that it's the best way to go (and would just go ahead and create a gem out of it). – thisismydesign Jan 22 '19 at 13:35
  • I imagine that these two gems you mentioned started out nice and lean. Then scope creep happened :) – Sergio Tulentsev Jan 22 '19 at 13:42
  • 1
    Definitely `fugit` is a good option, it's pretty recent and i less likely to be abandoned - as it's core for some widely used gems (rufus-scheduler and others) – rewritten Jan 22 '19 at 15:04
1

ActiveSupport provides you this:

3.minutes # => 180 seconds
3.minutes.to_i # => 180
(3.minutes + 5.hours).to_i # => 18180
Timo Schilling
  • 3,003
  • 1
  • 17
  • 29
  • That is not Golang-style. Golang duration is a string of a format like "3m", "5h" and so on, and I'd like to turn that string into the number of seconds described by the duration. Thanks for the suggestion though! – MaxVT Oct 20 '16 at 21:36