Class: SearchPath

Inherits:
Object
  • Object
show all
Defined in:
lib/search_path.rb,
lib/search_path/version.rb

Defined Under Namespace

Classes: FileNotFoundError, SearchPathNotAbsoluteError, SearchPathNotExistError

Constant Summary collapse

VERSION =
"0.0.2"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(search_paths, options = {}) ⇒ SearchPath

Initialize a new SearchPath instance with the given search paths.

Parameters

  • search_paths - The search paths to find a filename in.

Options

  • :verify_paths - If true verify the existence of each search path and raise an SearchPathNotExistError exception if path not exists.

Examples

search_path = SearchPath.new("/path1/to/files")
search_path = SearchPath.new(["/path1/to/files", "/path2/to/files"])

# => raises SearchPathNotAbsoluteError
search_path = SearchPath.new(["a/relative/path"])

# => raises SearchPathNotExistError for "/not/existing/path"
search_path = SearchPath.new(["/existing/path", "/not/existing/path"], :verify_paths => true)


39
40
41
42
43
44
# File 'lib/search_path.rb', line 39

def initialize(search_paths, options = {})
  @search_paths = Array(search_paths)

  verify_search_paths_are_absolute!
  verify_search_paths_exists! if options[:verify_paths] == true
end

Instance Attribute Details

#search_pathsObject (readonly)

Returns the value of attribute search_paths.



15
16
17
# File 'lib/search_path.rb', line 15

def search_paths
  @search_paths
end

Instance Method Details

#find(filename) ⇒ Object

Finds the given filename in the search paths. Returns the full path to the file or nil if the file could not be found in one of the search paths.

Parameters

  • filename - The filename to find.

Examples

search_path = SearchPath.new(["/path1/to/files", "/path2/to/files"])

# File "searched_file.txt" exists in "/path1/to/files"
search_path.find("searched_file.txt") # => "/path1/to/files/searched_file.txt"

# File "searched_file.txt" exists in "/path2/to/files"
search_path.find("searched_file.txt") # => "/path2/to/files/searched_file.txt"

# File "searched_file.txt" exists in none
search_path.find("searched_file.txt") # => nil


67
68
69
70
71
72
73
74
75
# File 'lib/search_path.rb', line 67

def find(filename)
  search_paths.each do |path|
    if File.exists?("#{path}/#{filename}")
      return "#{path}/#{filename}"
    end
  end

  nil
end

#find!(filename) ⇒ Object

Same as #find but raises FileNotFoundError exception if the file could not be found.



80
81
82
# File 'lib/search_path.rb', line 80

def find!(filename)
  find(filename) || raise_file_not_found!(filename)
end