29

Some book mentioned some gem to decorate numbers with #days, #megabytes, #minutes etc. Is this only in ActiveSupport, or is there a smaller gem that provides this functionality for use in (small) non-rails gems? I want to use this functionality as part of a DSL in a tiny little gem.

sawa
  • 165,429
  • 45
  • 277
  • 381
d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • I like this behavior too, and have often wanted to use it in my non-rails ruby projects. Good question... – jaydel Jun 21 '11 at 11:37

3 Answers3

39

I'm not sure if there's another gem available besides ActiveSupport, but it would be really straight-forward to make a small version yourself:

class Fixnum
  SECONDS_IN_DAY = 24 * 60 * 60

  def days
    self * SECONDS_IN_DAY
  end

  def ago
    Time.now - self
  end
end

3.days.ago #=> 2011-06-18 08:45:29 0200

from_now can be implemented like ago but with + self and weeks, hours etc. like days using different constants.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
Michael Kohl
  • 66,324
  • 14
  • 138
  • 158
  • 1
    This seems like it may be the way I end up going, thanks. I thought that the Numeric thing had started in somebody else's project and that ActiveSupport just merged it into their own source. I'm probably just imagining it though. – d11wtq Jun 21 '11 at 07:20
  • 1
    very nice job!! – Chris Habgood Feb 18 '18 at 00:11
9

ActiveSupport has this functionality. It was originally part of Rails but can now be used separately.

Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • 21
    This is correct but also note you can no longer just ```require 'activesupport'```. The OP will need to be a little more explicit about what they want to ```require``` from activesupport. If you just want time you can ```require "active_support/core_ext/numeric/time"``` – Caley Woods Jun 21 '11 at 05:05
  • I don't really want to depend on all of ActiveSupport for this :) That was sort of what I was trying to avoid. My Gem is just a single class with about 30 lines of code :P But thanks for the confirmation :) – d11wtq Jun 21 '11 at 07:18
  • @d11wtq then michael kohl's answer would be the way to go. Just extending the fixnum class with something like a ```days``` and ```ago``` method. – Caley Woods Jun 21 '11 at 15:53
  • 10
    its `require 'active_support/all'` nowadays – phoet Jan 28 '14 at 21:43
3

I found: https://github.com/kylewlacy/timerizer

Erik
  • 4,268
  • 5
  • 33
  • 49
  • Just what I was looking for. Not widely used or mature (most recent release is 0.3.0; 33 stars and 3 forks as I type this), but it _has_ been around a while, and looks to be a drop-in that won't force me to add the ActiveSupport crack pipe to my Hanami project. Thanks. – Jeff Dickey Apr 15 '18 at 17:34