Class: Ocran::FilePathSet

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/ocran/file_path_set.rb

Instance Method Summary collapse

Constructor Details

#initializeFilePathSet

Returns a new instance of FilePathSet.



10
11
12
# File 'lib/ocran/file_path_set.rb', line 10

def initialize
  @set = {}
end

Instance Method Details

#add(source, target) ⇒ Object



14
15
16
17
# File 'lib/ocran/file_path_set.rb', line 14

def add(source, target)
  add?(source, target)
  self
end

#add?(source, target) ⇒ self?

Adds a source and target path pair to the set and validates the paths before adding. This method performs various checks to ensure the source path is an absolute path and the target path is a relative path that does not include ‘.’ or ‘..’. If a conflict is detected (i.e., different source for the same target), it raises an exception.

Parameters:

  • source (String, Pathname)
    • The source file path; must be an absolute path.

  • target (String, Pathname)
    • The target file path; must be a relative path.

Returns:

  • (self, nil)

    Returns self if the path pair is added successfully, returns nil if the same source and target pair is already present.

Raises:

  • (ArgumentError)

    If the source is not an absolute path, if the target is not a relative path, or if the target includes ‘.’ or ‘..’.

  • (RuntimeError)

    If a conflicting source is found for the same target.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/ocran/file_path_set.rb', line 32

def add?(source, target)
  source = Pathname.new(source) unless source.is_a?(Pathname)
  source = source.cleanpath
  unless source.absolute?
    raise ArgumentError, "Source path must be absolute, given: #{source}"
  end

  target = Pathname.new(target) unless target.is_a?(Pathname)
  target = target.cleanpath
  unless target.relative?
    raise ArgumentError, "Target path must be relative, given: #{target}"
  end
  if %w(. ..).include?(target.each_filename.first)
    raise ArgumentError, "Relative paths such as '.' or '..' are not allowed, given: #{target}"
  end

  if (path = @set[target])
    if path.eql?(source)
      return nil
    else
      raise "Conflicting sources for the same target. Target: #{target}, Existing Source: #{path}, Given Source: #{source}"
    end
  end

  @set[target] = source
  self
end

#eachObject



60
61
62
63
# File 'lib/ocran/file_path_set.rb', line 60

def each
  return to_enum(__method__) unless block_given?
  @set.each { |target, source| yield(source, target) }
end

#to_aObject



65
66
67
# File 'lib/ocran/file_path_set.rb', line 65

def to_a
  each.to_a
end