MaxVT
MaxVT

Reputation: 13234

Is there a Ruby library for Golang-style duration parsing?

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!

Upvotes: 1

Views: 194

Answers (2)

thisismydesign
thisismydesign

Reputation: 25072

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

Upvotes: 2

Timo Schilling
Timo Schilling

Reputation: 3073

ActiveSupport provides you this:

3.minutes # => 180 seconds
3.minutes.to_i # => 180
(3.minutes + 5.hours).to_i # => 18180

Upvotes: 1

Related Questions