Class: DicomS::SharedFile

Inherits:
Object
  • Object
show all
Defined in:
lib/dicoms/shared_files.rb

Overview

Shared files can be concurrently accessed by diferent processes. They should never be large files, and update operations (reading, then writing) should always be quick, because processes trying to read the file while an update is going on are blocked.

Example

counter = SharedFile.new('counter')

counter.update do |contents|
  contents.to_i + 1
end

counter = counter.read.to_i

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}) ⇒ SharedFile

Returns a new instance of SharedFile.



22
23
24
25
# File 'lib/dicoms/shared_files.rb', line 22

def initialize(name, options = {})
  @name = name
  raise "A directory exists with that name" if File.directory?(@name)
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



27
28
29
# File 'lib/dicoms/shared_files.rb', line 27

def name
  @name
end

Instance Method Details

#exists?Boolean

Returns:

  • (Boolean)


29
30
31
# File 'lib/dicoms/shared_files.rb', line 29

def exists?
  File.exists?(@name)
end

#readObject

Read a file safely



50
51
52
53
54
55
# File 'lib/dicoms/shared_files.rb', line 50

def read
  File.open(@name, "r") do |file|
    file.flock File::LOCK_SH # this blocks until available
    file.read
  end
end

#update(&blk) ⇒ Object

Update a file safely.



34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dicoms/shared_files.rb', line 34

def update(&blk)
  File.open(@name, File::RDWR|File::CREAT, 0644) do |file|
    file.flock File::LOCK_EX
    if blk.arity == 1
      new_contents = blk.call(file.read)
    else
      new_contents = blk.call
    end
    file.rewind
    file.write new_contents
    file.flush
    file.truncate file.pos
  end
end

#write(contents) ⇒ Object



57
58
59
# File 'lib/dicoms/shared_files.rb', line 57

def write(contents)
  update { contents }
end