Class: FileLocator

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

Defined Under Namespace

Classes: S3File

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ FileLocator

Returns a new instance of FileLocator.



22
23
24
# File 'lib/file_locator.rb', line 22

def initialize(source)
  @source = source
end

Instance Attribute Details

#sourceObject (readonly)

Returns the value of attribute source.



6
7
8
# File 'lib/file_locator.rb', line 6

def source
  @source
end

Instance Method Details

#attachmentObject



83
84
85
86
87
88
89
90
91
92
# File 'lib/file_locator.rb', line 83

def attachment
  case uri.scheme
  when 's3'
    uri
  when 'file'
    File.open(location, 'r')
  else
    location
  end
end

#exist?Boolean Also known as: exists?

Returns:

  • (Boolean)


60
61
62
63
64
65
66
67
68
69
# File 'lib/file_locator.rb', line 60

def exist?
  case uri.scheme
  when 's3'
    S3File.new(uri).object.exists?
  when 'file'
    File.exist?(location)
  else
    false
  end
end

#locationObject



49
50
51
52
53
54
55
56
57
58
# File 'lib/file_locator.rb', line 49

def location
  case uri.scheme
  when 's3'
    S3File.new(uri).object.presigned_url(:get)
  when 'file'
    URI.decode(uri.path)
  else
    @uri.to_s
  end
end

#readerObject



72
73
74
75
76
77
78
79
80
81
# File 'lib/file_locator.rb', line 72

def reader
  case uri.scheme
  when 's3'
    S3File.new(uri).object.get.body
  when 'file'
    File.open(location, 'r')
  else
    Kernel.open(uri.to_s, 'r')
  end
end

#uriObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/file_locator.rb', line 26

def uri
  if @uri.nil?
    if source.is_a? File
      @uri = Addressable::URI.parse("file://#{URI.encode(File.expand_path(source))}")
    else
      encoded_source = source
      begin
        @uri = Addressable::URI.parse(encoded_source)
      rescue URI::InvalidURIError
        if encoded_source == source
          encoded_source = URI.encode(encoded_source)
          retry
        else
          raise
        end
      end

      @uri = Addressable::URI.parse("file://#{URI.encode(File.expand_path(source))}") if @uri.scheme.nil?
    end
  end
  @uri
end