preload
Jul 13

I was writing a Ruby program today that just needed a very simple way to control multiple web requests to a Sinatra server from querying a remote server at the same time. I would think that Sinatra does have some nice way to do this(and if you know it, please send me the link :) ), but I didn’t have time to dig into it, so I pulled out my old trusty Lockfile class.

The concept is very simple: Open a file, put a random string into it, close it. I use the random string to make sure that my process really did create the file, rather than another process running at the same time. The verify method can be called at any time to check that we still have the lock….well, that we are suppose to have the lock ;) If the file already exists, then you don’t get the lock. If you can’t open the file, then someone else must have just opened it, and again no lock.

Now the source… Continue reading »

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon
Tagged with:
Jul 12

There are a lot of posts out there about how to add commas to numbers, but I haven’t seen any that showed how to make it a method of the built-in number types. Its very easy actually, but for those who are beginner Rubyists, here’s how I did it:


class Bignum

  def commas
    self.to_s =~ /([^\.]*)(\..*)?/
    int, dec = $1.reverse, $2 ? $2 : ""
    while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
    end
    int.reverse + dec
  end

end    

class Float

  def commas
    self.to_s =~ /([^\.]*)(\..*)?/
    int, dec = $1.reverse, $2 ? $2 : ""
    while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
    end
    int.reverse + dec
  end

end

class Fixnum

  def commas
    self.to_s =~ /([^\.]*)(\..*)?/
    int, dec = $1.reverse, $2 ? $2 : ""
    while int.gsub!(/(,|\.|^)(\d{3})(\d)/, '\1\2,\3')
    end
    int.reverse + dec
  end

end

Its the same function added to the three main number classes(Bignum, Float, and Fixnum). You would use them like so:

irb(main):001:0> require 'exo/format'
=> true
irb(main):002:0> g = 123456789
=> 123456789
irb(main):003:0> g.commas
=> "123,456,789"
irb(main):004:0> f = 123456.7891
=> 123456.7891
irb(main):005:0> f.commas
=> "123,456.7891"
irb(main):006:0> b = 12347862389461237846192873461287346
=> 12347862389461237846192873461287346
irb(main):007:0> b.commas
=> "12,347,862,389,461,237,846,192,873,461,287,346"
irb(main):008:0>

(exo/format is just the filename I use for the code above) These methods have the added benefit of converting the number into a string so you don’t have to convert before printing out.

SociBook del.icio.us Digg Facebook Google Yahoo Buzz StumbleUpon