Sha256: 25f95a35cc8e8a0074cd1f46d57802a6190b1db77ebf610d8976ea78be9b2b14

Contents?: true

Size: 1.19 KB

Versions: 3

Compression:

Stored size: 1.19 KB

Contents

class Time
  
  def to_time #:nodoc:
    self
  end
  
  ##
  # Time in words since +time+ or now.
  #
  # === Examples
  #
  #   5.seconds.ago.in_words_since_now  # => less than one minute
  #   5.days.ago.in_words_since_now     # => 5 days
  #   1.month.ago.in_words_since_now    # => 1 month
  #   101.years.ago.in_words_since_now  # => nil
  #
  #   "the article was published #{article.created_at.in_words_since_now || 'hundreds of years' } ago"  
  #   # => the article was published 15 minutes ago
  #

  def in_words_since time = Time.now
    time = time.to_time
    return if self > time
    seconds = (time - self).to_i
    # TODO: abstract this out
    pluralize = lambda do |type| 
      n = seconds.send(:"to_#{type}s")
      n == 1 ? "one #{type}" : "#{n} #{type}s"
    end
    case seconds
    when 0..60                ; 'less than one minute'
    when 1.minute..60.minutes ; pluralize[:minute]
    when 1.hour..24.hours     ; pluralize[:hour]
    when 1.day..7.days        ; pluralize[:day]
    when 1.week..4.weeks      ; pluralize[:week]
    when 1.month..12.months   ; pluralize[:month]
    when 1.year..99.years     ; pluralize[:year]
    end
  end
  alias :in_words_since_now :in_words_since
  
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rext-0.7.0 lib/rext/time/helpers.rb
rext-0.6.2 lib/rext/time/helpers.rb
rext-0.6.1 lib/rext/time/helpers.rb