ぬけラボ

φ(..)メモメモ

Ruby193でファイルカウンター

Rubyでファイルカウンターが必要になったのでメモ
ここが参考になりました
http://doc.ruby-lang.org/ja/1.9.2/method/File/i/flock.html

#encoding: utf-8
class Counter                                          
  def initialize(file)                                 
    @file = file                                       
  end                                                  

  def increment
    begin
      until File.exist?(@file) do
        open(@file, "w") do |f|
          f.write 0
        end
      end
      counter = 0
      open(@file, "r+") do |f|
        f.flock(File::LOCK_EX)
        counter = f.gets.to_i + 1
        f.rewind
        f.write counter
        f.flush
        f.truncate(f.pos)
        f.flock(File::LOCK_UN)
      end
      format("%08d",counter)
    rescue => ex
      puts ex
      "E" + [*0..9, *'a'..'z'].sample(7).join
    end
  end
end

cnt = Counter.new("count.txt")
puts cnt.increment #=> 0000001

同時にアクセスしてみる

$ ruby counter.rb & ruby counter.rb & ruby counter.rb & ruby couter.rb & ruby counter.rb
0000001
0000002
0000003
0000004
0000005