Class: Textus::Infra::Refresh::Lock

Inherits:
Object
  • Object
show all
Defined in:
lib/textus/infra/refresh/lock.rb

Instance Method Summary collapse

Constructor Details

#initialize(root:, key:) ⇒ Lock

Returns a new instance of Lock.



7
8
9
10
11
12
# File 'lib/textus/infra/refresh/lock.rb', line 7

def initialize(root:, key:)
  @root = root
  @key  = key
  @path = File.join(root, ".locks", "#{safe_key}.lock")
  @file = nil
end

Instance Method Details

#releaseObject



28
29
30
31
32
33
34
# File 'lib/textus/infra/refresh/lock.rb', line 28

def release
  return unless @file

  @file.flock(File::LOCK_UN)
  @file.close
  @file = nil
end

#try_acquireObject

rubocop:disable Naming/PredicateMethod



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/textus/infra/refresh/lock.rb', line 14

def try_acquire # rubocop:disable Naming/PredicateMethod
  FileUtils.mkdir_p(File.dirname(@path))
  @file = File.open(@path, File::RDWR | File::CREAT, 0o644)
  acquired = @file.flock(File::LOCK_EX | File::LOCK_NB)
  unless acquired
    @file.close
    @file = nil
    return false
  end
  @file.write(Process.pid.to_s)
  @file.flush
  true
end