Code Monkey home page Code Monkey logo

ruby-duration's Introduction

ruby-duration

Duration is an immutable type that represents some amount of time with accuracy in seconds.

A lot of the code and inspirations is borrowed from duration lib, which is a mutable Duration type with lot more features.

Help Wanted!

If you use ruby-duration and want to take over the project, let me know.

Maintainers Wanted

Features

  • Representation of time in weeks, days, hours, minutes and seconds.
  • Construtor can receive the amount of time in seconds or a Hash with unit and amount of time.
  • Format method to display the time with i18n support.
  • Mongoid serialization support. Use require 'duration/mongoid'.
  • Tested on mri 1.9.3 and jruby. Kudos to rvm!

Show me the code

constructor

Duration.new(100) => #<Duration: minutes=1, seconds=40, total=100>
Duration.new(:hours => 5, :minutes => 70) => #<Duration: hours=6, minutes=10, total=22200>

format

Duration.new(:weeks => 3, :days => 1).format("%w %~w and %d %~d") => "3 weeks and 1 day"
Duration.new(:weeks => 1, :days => 20).format("%w %~w and %d %~d") => "3 weeks and 6 days"
Duration.new(:weeks => 1, :days => 20).iso8601 => "P3W6DT0H0M0S"
Duration.new("P6DT5S") => #<Duration: days=6, seconds=5, total=518405>

Mongoid support

The current version of this gem supports Mongoid >= 3.0.0. For lower Mongoid versions try:

    require 'duration/mongoid'

    class MyModel
      include Mongoid::Document
      field :duration, type => Duration
    end

Dependencies

The current version of this gem runs only on Ruby Versions >= 1.9.3. If you are running a older version of Ruby try:

Note on Patches/Pull Requests

  • Fork the project.
  • Make your feature addition or bug fix.
  • Add tests for it. This is important so I don't break it in a future version unintentionally.
  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

License

Copyright (c) 2010 Jose Peleteiro

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

ruby-duration's People

Contributors

adamvoss avatar amartinsn avatar gcirne avatar gdavison avatar glennpratt avatar jacobevelyn avatar josedonizetti avatar olleolleolle avatar peleteiro avatar sanemat avatar smcabrera avatar ukstv avatar xiy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ruby-duration's Issues

I18n broken dependency

I18n is being depended on by Duration#format but not required anywhere.

Something in the test environment seems to be indirectly loading I18n, but I'm not sure what. Either way, in Rails and in the tests, it's loaded elsewhere, so the bug is not apparent.

However, outside of these environments:

ruby -I'lib' -r'ruby-duration' -e 'puts Duration.new.format("%s")'
.../ruby-duration/lib/duration.rb:149:in `format': \
  uninitialized constant Duration::I18n (NameError)

Can be fixed by loading i18n:

ruby -I'lib' -r'ruby-duration' -r'i18n' -e 'puts Duration.new.format("%s seconds")'
0 seconds

Tested with Ruby 1.9.2p0 on Linux and Mac OS.

Thanks for picking up the reins from the old duration gem.. apart from being abandoned it seems to be broken under Ruby 1.9 because of multi-byte chars declared in a US-ASCII context.. or something.

Cheers!
Paul

Adding duration to time

Would be great if one could add a duration to time, yielding a new time instance.

Time.now + Duration.new(:days => 1) #=> time_at_one_day_from_now

Ruby's coerce should also be helpful here, so that the ordering doesn't matter:


# Similarly, I would expect
Duration.new(:days => 2) + Time.now === Time.now.advance(:days => 2)

# Currently this is instead:
Duration.new(:days => 2) + Time.now # => seconds since 1970 + 2 days (as `Duration`)

# While this is one possible interpretation It's fairy non-sensical, 
# i.e. it's not very useful, while a result that returned a new time instance 
# would make durations much more useable!

SyntaxError

Hi,

I'm receiving a SyntaxError upon loading the library under ruby 1.9.3p0:

irb(main):001:0> require "duration"
SyntaxError: /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/duration-0.1.0/lib/duration/localizations/korean.rb:6: invalid multibyte char (US-ASCII)
/Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/duration-0.1.0/lib/duration/localizations/korean.rb:6: invalid multibyte char (US-ASCII)
/Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/duration-0.1.0/lib/duration/localizations/korean.rb:6: syntax error, unexpected $end, expecting keyword_end
      PLURALS   = %w(초 분 시간 일 주)
                       ^
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/duration-0.1.0/lib/duration/localizations.rb:3:in `<top (required)>'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/gems/1.9.1/gems/duration-0.1.0/lib/duration.rb:4:in `<top (required)>'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:59:in `require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:59:in `rescue in require'
    from /Users/administrator/.rbenv/versions/1.9.3-p0/lib/ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
    from (irb):1
    from /Users/administrator/.rbenv/versions/1.9.3-p0/bin/irb:12:in `<main>'

Add a format for correct typographic marks for minutes and seconds

On the site I run we use a helpers to use the prime( ′) and double prime (″) for minutes and seconds. Yes, we are pedants.

I'd be happy to work up a patch to provide formats for this, if there is interest.

If so, should there be an option to use html entities for these, as well as UTF8?

invalid multibyte char (US-ASCII) (SyntaxError)

$ rails c
~/.rvm/gems/ruby-1.9.3-p429/gems/activesupport-3.2.17/lib/active_support/dependencies.rb:251:in `require': /Users/.rvm/gems/ruby-1.9.3-p429/gems/duration-0.1.0/lib/duration/localizations/korean.rb:7: invalid multibyte char (US-ASCII) (SyntaxError)
/Users/.rvm/gems/ruby-1.9.3-p429/gems/duration-0.1.0/lib/duration/localizations/korean.rb:7: invalid multibyte char (US-ASCII)
/Users/.rvm/gems/ruby-1.9.3-p429/gems/duration-0.1.0/lib/duration/localizations/korean.rb:7: syntax error, unexpected $end, expecting keyword_end

The encoding needs to be added at the top of korean.rb in the duration gem. I'm not sure if this can be updated upstream in a reasonable amount of time or if it will need a fork. Thoughts?

# encoding: utf-8

Removing active-support issues causes uncaught exception

./vendor/bundler/ruby/2.2.0/gems/i18n-0.7.0/lib/i18n.rb:284:in `enforce_available_locales!': :en is not a valid locale (I18n::InvalidLocale)
    from ./vendor/bundler/ruby/2.2.0/gems/i18n-0.7.0/lib/i18n.rb:151:in `translate'
    from ./vendor/bundler/ruby/2.2.0/gems/ruby-duration-3.2.2/lib/duration.rb:247:in `i18n_for'
    from ./vendor/bundler/ruby/2.2.0/gems/ruby-duration-3.2.2/lib/duration.rb:193:in `format'

string output

Currently outputting as a string gives you the following:

Duration.new(1000).to_s
=> "#<Duration:0x007fc7f28f5ce8>"

I'd love to implement a to_s function that would cause durations to output a little more like the way the Time class works:

Time.new.to_s
=> "2015-03-02 17:59:27 -0500"

Something like this:

Duration.new(1000).to_s
=> "00:16:40"

The only issue I can think of is that you allow for days and weeks and I'm not sure what format those should be outputted in...thoughts?

Error with negative quantities

Unless I'm missing something really obvious there seems to be a problem with negative numbers. For example if I instantiate a couple of Duration objects...

a = Duration.new(10)
=> #<Duration:0x007f21aa066c88 @seconds=10, @negative=false, @total=10, @weeks=0, @days=0, @hours=0, @minutes=0>
b = Duration.new(-5)
=> #<Duration:0x007f21a9e97150 @seconds=5, @negative=true, @total=5, @weeks=0, @days=0, @hours=0, @minutes=0>

They correctly report whether or not they are negative:

a.negative?
=> false
b.negative?
=> true

But then if I try to add a couple durations together the negative duration doesn't seem to behave as negative:

c = a + b
=> #<Duration:0x007f21a902f180 @seconds=15, @negative=false, @total=15, @weeks=0, @days=0, @hours=0, @minutes=0>

I get a positive 15.

Doesn't fully support actual ISO8601 Duration format

Duration has years months, days, hours, minutes, seconds. So why not support all of these?

irb(main):004:0>  d = Duration.new('P3Y6M4DT12H30M5S')
=> #<Duration:0x007fdb4ea67df0 @seconds=5, @negative=false, @total=110766605, @weeks=183, @days=1, @hours=0, @minutes=30>
irb(main):005:0> d.iso8601
=> "P1282DT30M5S"

Shouldn't the output return the same format as the input?

miliseconds

Di you plan on implementing miliseconds? I started using this for an ffmpeg video editing project, and a lot can happen in a second on film. Ffmpeg has a function that tells you where a video fades to black at say at second 3535.3432. I wanted to store and manipulate these as Duration objects, but it's just not fine grained enough. Seem like a useful thing to have.

Any thoughts?

Is it working with Mongoid 4?

Hi,

I'm trying to assign duration to a field.
Using Rails 4.1 and Mongoid 4
Is it not working with this stack or am I doing something wrong?
Here is what I do:

require 'duration/mongoid'
class Price
  include Mongoid::Document

  embedded_in :workdone 
  field :variation_id   
  field :price, type: Float
  field :discount, type: Integer
  field :duration, type: Duration
  price = workdone.prices.build
          price.variation_id =Moped::BSON::ObjectId.from_string(var._id )  
          pricelow = Price.get_high_lows(price.variation_id ,self)          
          price.price =  pricelow.present? ? pricelow[0].price : var.base_price.to_f
          price.discount = pricelow.present? ? pricelow[0].discount : 0
          price.duration = Duration.new(:minutes=>60)
          price.save!
...


=> #<Price _id: 53ada69963616e7250140000, variation_id: BSON::ObjectId('53a4063a63616e291c3e0000'), price: 19.0, discount: 0, duration: nil>

ruby-duration raise error when used with activesupport >= 4.2

I've encountered error when used with latest activesupport (>= 4.2).

% ruby -v
ruby 2.1.5p273 (2014-11-13 revision 48405) [i386-mingw32]

% bundle exec ruby sample.rb
DL is deprecated, please use Fiddle
C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/module/deprecation.rb:21:in `deprecate': uninitialized constant ActiveSupport::Deprecation (NameError)
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/class/delegating_attributes.rb:26:in `<class:Class>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/class/delegating_attributes.rb:6:in `<top (required)>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/class.rb:2:in `require'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext/class.rb:2:in `<top (required)>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext.rb:2:in `require'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext.rb:2:in `block in <top (required)>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext.rb:1:in `each'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/activesupport-4.2.0/lib/active_support/core_ext.rb:1:in `<top (required)>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/ruby-duration-3.2.0/lib/duration.rb:3:in `require'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/ruby-duration-3.2.0/lib/duration.rb:3:in `<top (required)>'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/ruby-duration-3.2.0/lib/ruby-duration.rb:2:in `require'
        from C:/Ruby21/lib/ruby/gems/2.1.0/gems/ruby-duration-3.2.0/lib/ruby-duration.rb:2:in `<top (required)>'
        from sample.rb:1:in `require'
        from sample.rb:1:in `<main>'

As for minimum code for reproduce, please refer my gist.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.