Module: URI::FileCommon

Included in:
CoreFile, WinFile
Defined in:
lib/file-uri/common.rb

Constant Summary collapse

COMPONENT =
%i[
  scheme
  userinfo host port
  path
  query
  fragment
]
COLON =
?:.freeze
SLASH =
?/.freeze
DBL_SLASH =
'//'.freeze
BACKSLASH =
'\\'.freeze
DBL_BACKSLASH =
'\\\\'.freeze
LOCALHOST =
'localhost'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.build(args) ⇒ Object



14
15
16
17
# File 'lib/file-uri/common.rb', line 14

def self.build(args)
  tmp = Util.make_components_hash(self, args)
  super(tmp)
end

Instance Method Details

#local?(localhost: true) ⇒ Boolean

localhost:

* :any  => any non-empty host is local
* true  => 'file://localhost/' is local, 'file://example.com/' is non-local
* false => 'file://localhost/' is non-local

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
# File 'lib/file-uri/common.rb', line 26

def local? localhost: true
  if host && !host.empty?
    return true if localhost == :any
    return localhost && (host.downcase == LOCALHOST)
  elsif path && path.start_with?(DBL_SLASH)
    return false
  end
  true
end

#open(*args, localhost: :true, &block) ⇒ Object

open( [mode [, perm]] [, opt]) –> io or nil open( [mode [, perm]] [, opt]) {|io| block } –> obj

See Kernel#open, URI::File#to_file_path



75
76
77
# File 'lib/file-uri/common.rb', line 75

def open *args, localhost: :true, &block
  Kernel::open to_file_path(localhost: localhost), *args, &block
end

#to_file_path(localhost: true) ⇒ Object

localhost:

* :any  => any non-empty host is local
* true  => 'file://localhost/' is local, 'file://example.com/' is non-local
* false => 'file://localhost/' is non-local


43
44
45
46
# File 'lib/file-uri/common.rb', line 43

def to_file_path localhost: true
  raise "no local path for non-local URI #{to_s}" unless local?(localhost: localhost)
  path
end

#to_unc(localhost: true) ⇒ Object

localhost:

* :any  => any non-empty host is local
* true  => 'file://localhost/' is local, 'file://example.com/' is non-local
* false => 'file://localhost/' is non-local


55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/file-uri/common.rb', line 55

def to_unc localhost: true
  if host && !host.empty?
    if localhost != :any && (!localhost || (host.downcase != LOCALHOST))
      unc = DBL_BACKSLASH + host
      unc += COLON + port if port
      unc += path.gsub(%r[/], BACKSLASH)
      return unc
    end
  elsif path.start_with? DBL_SLASH
    return path.gsub(%r[/], BACKSLASH)
  end
  raise "no UNC conversion for local URI #{to_s}"
end