File: once.rb

package info (click to toggle)
ruby-tins 1.32.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,248 kB
  • sloc: ruby: 6,659; makefile: 3
file content (25 lines) | stat: -rw-r--r-- 559 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
module Tins
  module Once
    include File::Constants

    module_function

    def only_once(lock_filename = nil, locking_constant = nil)
      lock_filename ||= $0
      locking_constant ||= LOCK_EX
      f = File.new(lock_filename, RDONLY)
      f.flock(locking_constant) and yield
    ensure
      if f
        f.flock LOCK_UN
        f.close
      end
    end

    def try_only_once(lock_filename = nil, locking_constant = nil, &block)
      only_once(lock_filename, locking_constant || LOCK_EX | LOCK_NB, &block)
    end
  end
end

require 'tins/alias'