<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: freeze code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 28 Aug 2008 19:16:49 GMT</pubDate>
    <description>DZone Snippets: freeze code</description>
    <item>
      <title>Make Time "Stand Still" in Ruby</title>
      <link>http://snippets.dzone.com/posts/show/4776</link>
      <description>When writing tests, it's sometimes difficult to test results of methods that use current time. Two calls to Time.now can give different results and cause test failures. Here is some code that lets you execute a block during which Time.now will return a consistent value:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class Time&lt;br /&gt;&lt;br /&gt;  # this code adds a Time.freeze method to make time "stand still"&lt;br /&gt;  # during execution of a block. This can be helpful during testing of&lt;br /&gt;  # methods that depend on Time.new or Time.now&lt;br /&gt;  #&lt;br /&gt;  # Example:&lt;br /&gt;  #&lt;br /&gt;  #   Time.freeze do&lt;br /&gt;  #      puts Time.new.to_f&lt;br /&gt;  #      # ... do stuff; real time passes&lt;br /&gt;  #      puts Time.new.to_f     # outputs same time as above&lt;br /&gt;  #   end&lt;br /&gt;  #   # ... time returns to normal&lt;br /&gt;  #&lt;br /&gt;  # An optional Time object may be passed to freeze to a specific time:&lt;br /&gt;  #&lt;br /&gt;  #   Time.freeze(Time.at(2007, 11, 15)) do&lt;br /&gt;  #      # ...&lt;br /&gt;  #   end&lt;br /&gt;  #&lt;br /&gt;  # While inside the block, Time.frozen? will return true&lt;br /&gt;&lt;br /&gt;  class &lt;&lt; self&lt;br /&gt;&lt;br /&gt;    def now&lt;br /&gt;      @time || orig_new&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    alias_method :orig_freeze, :freeze&lt;br /&gt;    alias_method :orig_new, :new&lt;br /&gt;    alias_method :new, :now&lt;br /&gt;&lt;br /&gt;    # makes time "stand still" during execution of a block. if no time is&lt;br /&gt;    # supplied, the current time is used. While in the block, Time.new and&lt;br /&gt;    # Time.now will always return the "frozen" value.&lt;br /&gt;    def freeze(time = nil)&lt;br /&gt;      raise "A block is required" unless block_given?&lt;br /&gt;      begin&lt;br /&gt;        prev = @time&lt;br /&gt;        @time = time || now&lt;br /&gt;        yield&lt;br /&gt;      ensure&lt;br /&gt;        @time = prev&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;    def frozen?&lt;br /&gt;      !@time.nil?&lt;br /&gt;    end&lt;br /&gt;&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;</description>
      <pubDate>Thu, 15 Nov 2007 21:36:47 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4776</guid>
      <author>bshow (Bob Showalter)</author>
    </item>
  </channel>
</rss>
