Module: OpenGCS

Defined in:
lib/open-gcs.rb,
lib/open-gcs/file.rb,
lib/open-gcs/version.rb

Defined Under Namespace

Modules: File

Constant Summary collapse

TARGET_SCHEME =
"gs"
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.get_path_info(uri) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/open-gcs.rb', line 41

def self.get_path_info(uri)
  unless String === uri
    []
  else
    parsed_uri = URI.parse(uri)
    [*parsed_uri.select(:scheme, :host), parsed_uri&.path.delete_prefix("/")]
  end
end

.open_gcs(uri, *rest, **options, &block) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/open-gcs.rb', line 8

def self.open_gcs(uri, *rest, **options, &block)
  scheme, bucket, path = get_path_info(uri)

  unless scheme == TARGET_SCHEME
    raise(ArgumentError, "Invalid uri: #{uri} (This method is only support for gcs object uri.")
  end

  if String === rest.first || Integer === rest.first
    mode = rest.first
  else
    mode = options[:mode]
  end
  if !mode.nil? && !mode.match?(/\Ar[bt]?(?:\Z|:([^:]+))/) && mode != ::File::RDONLY
    raise(ArgumentError, "Invalid access mode: #{mode}. (This method is only support for read mode.)")
  end

  begin
    tf = File.download(bucket, path, **options.select { |key| File::OPTION_KEYS.include?(key) })
    file = ::File.open(tf.path, *rest, **options.reject { |key| File::OPTION_KEYS.include?(key) })
    if block_given?
      begin
        yield file
      ensure
        tf.close!
      end
    else
      file
    end
  ensure
    tf&.close if tf&.path
  end
end