Extending Ruby’s Time class with ‘before?’ and ‘after?’

The mixin below allows comparison between two Time objects using the more intuitive and natural-sounding before? and after? methods.

Some examples (using Rails’ ActiveSupport Time extensions or (preferred) the ‘units’ gem):

2.minutes.ago.after? Time.now # =>; false
Time.now.before? 2.hours.from_now # => true
module BeforeAndAfter

  LEFT_SIDE_LARGER  = 1
  RIGHT_SIDE_LARGER = -1
  EQUAL             = 0
  ACCEPTABLE_SWITCH_VALUES = [ :before , :after ]

  def before?(input_time)
    return comparison(:before, input_time)
  end

  def after?(input_time)
    return comparison(:after, input_time)
  end

private

  def comparison(switch, input_time)

    raise ArgumentError, "bad comparison switch" unless ACCEPTABLE_SWITCH_VALUES.include? switch

    comparison_result = self <=> input_time

    case comparison_result
      when LEFT_SIDE_LARGER
        case switch
          when :before
            return false
          when :after
            return true
        end
      when RIGHT_SIDE_LARGER
        case switch
          when :before
            return true
          when :after
            return false
        end
      when EQUAL
        return false
    end
  end
end

Time.send :include , BeforeAndAfter

Read more from the ruby category. If you would like to leave a comment, click here: . or stay up to date with this post via RSS, or you can Trackback from your site.
Social Bookmark : Technorati, Digg, de.licio.us, Yahoo, Blinkbits, Blogmarks, Google, Magnolia.

Leave a Comment

Name (required)

Email (required)

Website

Comments

2 Comments so far

  1. Yury February 9, 2008 8:03 am

    Comments are back!

  2. jon March 19, 2008 10:00 pm

    I think the comments look just dandy! What’s the problem! :)