Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 49 total  RSS 

Displaying the difference between times in Ruby

This function converts the number of seconds into hours, minutes, and seconds.

   1  require 'time'
   2  
   3  def seconds_fraction_to_time(seconds)
   4    hours = mins = 0
   5    if seconds >=  60 then
   6      mins = (seconds / 60).to_i 
   7      seconds = (seconds % 60 ).to_i
   8  
   9      if mins >= 60 then
  10        hours = (mins / 60).to_i 
  11        mins = (mins % 60).to_i
  12      end
  13    end
  14    [hours,mins,seconds]
  15  end
  16  
  17  departed_house = Time.parse("07:34")
  18  arrived_at_supermarket = Time.parse("09:10")
  19  travel_duration_in_seconds =  arrived_at_supermarket - departed_house
  20  
  21  hours, minutes, seconds = seconds_fraction_to_time(travel_duration_in_seconds)
  22  
  23  puts "The journey from my home to the supermarket took #{hours} hour(s), #{minutes} minutes, and #{seconds} seconds."

Output:
The journey from my home to the supermarket took 1 hour(s), 36 minutes, and 0 seconds.

References:
- Class: Time [ruby-doc.org]
- Working with Dates and Times in Ruby [techotopia.com]
- Numbers in Ruby [rubylearning.com]

Making time for Ruby

   1  b = Time.parse("17:30")

=> Wed Aug 20 17:30:00 +0100 2008

Reference:
Class: Time [ruby-doc.org]

A user friendly elapsed time with Ruby

This Ruby code outputs a user friendly elapsed time or a historical date if the event was more than 24 hours ago.
   1  
   2  def didwhen(old_time)
   3  
   4    val = Time.now - old_time
   5    #puts val
   6    if val < 10 then
   7      result = 'just a moment ago'
   8    elsif val < 40  then
   9      result = 'less than ' + (val * 1.5).to_i.to_s.slice(0,1) + '0 seconds ago'
  10    elsif val < 60 then
  11      result = 'less than a minute ago'
  12    elsif val < 60 * 1.3  then
  13      result = "1 minute ago"
  14    elsif val < 60 * 50  then
  15      result = "#{(val / 60).to_i} minutes ago"
  16    elsif val < 60  * 60  * 1.4 then
  17      result = 'about 1 hour ago'
  18    elsif val < 60  * 60 * (24 / 1.02) then
  19      result = "about #{(val / 60 / 60 * 1.02).to_i} hours ago"
  20    else
  21      result = old_time.strftime("%H:%M %p %B %d, %Y")
  22  
  23    end
  24    result
  25  end


Inspired by Twitter.

TimeLine //JavaScript Class




Simulates the Adobe Flash timeline. You define the amount of frames, the speed in fps (frames per second) and, at each frame passage an event is called, useful for animations.

[UPDATED CODE AND HELP CAN BE FOUND HERE]



   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/classes/timeline [v1.0]
   4  
   5  TimeLine = function(fps, f){
   6  	this.fps = fps, this.frames = f;
   7  };
   8  with({o: TimeLine, $: TimeLine.prototype}){
   9  	o.timers = [];
  10  	$.running = !!($.current = +(o.timer = $.time = null));
  11  	o.run = function(){
  12  		var o = this;
  13  		o.timer || (o.timer = setInterval(function(){
  14  			for(var h, d = +(new Date), t = o.timers, i = t.length; i--;){
  15  				(!t[i].running || ((d - t[i].time) / (1e3 / t[i].fps) > t[i].current + 1 &&
  16  				t[i].onframe(++t[i].current), t[i].current >= t[i].frames)) &&
  17  				(h = t.splice(i, 1)[0], h.stop(1));
  18  			}
  19  		}, 1));
  20  	};
  21  	$.start = function(c){
  22  		var o = this, t = TimeLine;
  23  		if(o.running) return;
  24  		o.running = true, o.current = c || 0;
  25  		o.time = new Date, o.onstart && o.onstart();
  26  		if(!o.onframe || o.frames <= 0 || o.fps <= 0)
  27  			return o.stop(1);
  28  		t.timers.push(this), t.run();
  29  	};
  30  	$.stop = function(){
  31  		var o = this;
  32  		o.running = false;
  33  		if(!TimeLine.timers.length)
  34  			TimeLine.timer = clearInterval(TimeLine.timer), null;
  35  		arguments.length && o.onstop && o.onstop();
  36  	};
  37  }


Example

   1  
   2  
   3  <div id="box" style="position: absolute; top: 100px; background: #efe; width: 100px; height: 100px">25 fps</div>
   4  <div id="box2" style="position: absolute; top: 300px; background: #ff9; width: 100px; height: 100px">12 fps</div>
   5  
   6  <strong>TimeLine working together with the ease in quad function.</strong><br />
   7  
   8  <script type="text/javascript">
   9  Math.ease = function (t, b, c, d) {
  10  	if ((t /= d / 2) < 1)
  11  		return c / 2 * t * t + b;
  12  	return -c / 2 * (--t * (t - 2) - 1) + b;
  13  };
  14  
  15  var o = new TimeLine(25, 50), d = document, b = d.getElementById("box");
  16  o.onframe = function(){
  17  	b.style.left = Math.ease(this.current, 0, 400, 30) + "px";
  18  };
  19  o.onstart = function(){
  20  	d.body.appendChild(d.createTextNode("Started"));
  21  };
  22  o.onstop = function(){
  23  	d.body.appendChild(d.createTextNode(" - Finished (" + (((new Date) - this.time)) + " msec)"))
  24  	d.body.appendChild(d.createElement("br"));
  25  	this.start();
  26  };
  27  o.start();
  28  
  29  
  30  var o2 = new TimeLine(12, 50), b2 = d.getElementById("box2");
  31  o2.onframe = function(){
  32  	b2.style.left = Math.ease(this.current, 0, 400, 30) + "px";
  33  };
  34  o2.onstop = function(){
  35  	this.start();
  36  };
  37  o2.start();
  38  </script>

Measuring the elapsed time

This Ruby code measures how long it takes to display the message "hello world".
   1  
   2  def test_method(statement)
   3    start_time = Time.now
   4    eval(statement)
   5    end_time = Time.now
   6    end_time - start_time
   7  end
   8  
   9  statement = "sleep 1.5; puts 'hello world'"
  10  elapsed_time = test_method(statement)
  11  puts "elapsed time : #{elapsed_time}"

output
   1  
   2  hello world
   3  elapsed time : 1.499266

Ruby Servlets

This WEBrick example demonstrates a basic servlet which displays the current time. Source code copied from At the Forge - Getting Started with Ruby [linuxjournal.com].

   1  
   2  #!/sw/bin/ruby
   3  require 'webrick'
   4  include WEBrick
   5  
   6  # ---------------------------------------------
   7  # Define a new class
   8  class CurrentTimeServlet
   9    < WEBrick::HTTPServlet::AbstractServlet
  10  
  11    def do_GET(request, response)
  12      response['Content-Type'] = 'text/plain'
  13      response.status = 200
  14      response.body = Time.now.to_s + "\n"
  15    end
  16  end
  17  
  18  # ----------------------------------------------
  19  # Create an HTTP server
  20  s = HTTPServer.new(
  21    :Port            => 8000,
  22    :DocumentRoot    => "/usr/local/apache/htdocs/"
  23  )
  24  
  25  s.mount("/time", CurrentTimeServlet)
  26  
  27  # When the server gets a control-C, kill it
  28  trap("INT"){ s.shutdown }
  29  
  30  # Start the server
  31  s.start

e.g. http://localhost:8001/time
output
   1  
   2  Mon Mar 10 23:06:58 +0000 2008

Reference: http://www.webrick.org/

Creating a DateTime object with Ruby

This example creates a date and time variable which represents 22nd March 2008 4:30pm and 12 seconds.
   1  
   2  d2 = DateTime.new(y=200,m=3,d=22, h=16,min=30,s=12)

or convert a date string into a DataTime object:
   1  
   2  "17/03/2009 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
   3  d2 = DateTime.new(y=$3.to_i,m=$2.to_i,d=$1.to_i, h=$4.to_i,min=$5.to_i,s=$6.to_i)

or convert a date string into a Time object:
   1  
   2  "22/03/2008 17:48:00"[/(\d+)\/(\d+)\/(\d+)\s(\d+):(\d+):(\d+)/]
   3  iyear = $3.to_i; imonth = $2.to_i; iday = $1.to_i; ihour = $4.to_i; imin = $5.to_i; isec = $6.to_i
   4  twork = Time.local(iyear,imonth,iday,ihour,imin,isec) 
   5  puts 'we still have time to party' if Time.now < twork 

Reference:
Class: DateTime [ruby-doc.org]
Class: Time [ruby-doc.org]

before? and after? - Ruby Time class mixin

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):

   1  2.minutes.ago.after? Time.now # => false


   1  Time.now.before? 2.hours.from_now # => true


   1  module BeforeAndAfter
   2  
   3    LEFT_SIDE_LATER  = 1
   4    RIGHT_SIDE_LATER = -1
   5    
   6    def before?(input_time)
   7      (self <=> input_time) == RIGHT_SIDE_LATER
   8    end
   9    
  10    def after?(input_time)
  11      (self <=> input_time) == LEFT_SIDE_LATER
  12    end
  13  end
  14  
  15  Time.send :include , BeforeAndAfter

Find all rows for a certain day; Count days between two dates

   1  
   2  # Find all rows created on a certain day; Rails apparently has a built-in :db string format
   3  self.find(:all, :conditions => ["created_at >= ? AND created_at <= ?", day.beginning_of_day.to_s(:db), day.end_of_day.to_s(:db)])
   4  
   5  # Find number of days between two dates
   6  def days_between_dates(first, last)
   7    (YMD(last) - YMD(first))
   8  end
   9  
  10  def YMD(date)
  11    date.to_date.to_s.gsub("-", "").to_i
  12  end

Make Time "Stand Still" in Ruby

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:

   1  
   2  class Time
   3  
   4    # this code adds a Time.freeze method to make time "stand still"
   5    # during execution of a block. This can be helpful during testing of
   6    # methods that depend on Time.new or Time.now
   7    #
   8    # Example:
   9    #
  10    #   Time.freeze do
  11    #      puts Time.new.to_f
  12    #      # ... do stuff; real time passes
  13    #      puts Time.new.to_f     # outputs same time as above
  14    #   end
  15    #   # ... time returns to normal
  16    #
  17    # An optional Time object may be passed to freeze to a specific time:
  18    #
  19    #   Time.freeze(Time.at(2007, 11, 15)) do
  20    #      # ...
  21    #   end
  22    #
  23    # While inside the block, Time.frozen? will return true
  24  
  25    class << self
  26  
  27      def now
  28        @time || orig_new
  29      end
  30  
  31      alias_method :orig_freeze, :freeze
  32      alias_method :orig_new, :new
  33      alias_method :new, :now
  34  
  35      # makes time "stand still" during execution of a block. if no time is
  36      # supplied, the current time is used. While in the block, Time.new and
  37      # Time.now will always return the "frozen" value.
  38      def freeze(time = nil)
  39        raise "A block is required" unless block_given?
  40        begin
  41          prev = @time
  42          @time = time || now
  43          yield
  44        ensure
  45          @time = prev
  46        end
  47      end
  48  
  49      def frozen?
  50        !@time.nil?
  51      end
  52  
  53    end
  54  end
« Newer Snippets
Older Snippets »
Showing 1-10 of 49 total  RSS