Class: BFS::Bucket::InMem

Inherits:
Abstract show all
Defined in:
lib/bfs/bucket/in_mem.rb

Overview

InMem buckets are useful for tests

Defined Under Namespace

Classes: Entry

Instance Attribute Summary

Attributes inherited from Abstract

#encoding, #perm

Instance Method Summary collapse

Methods inherited from Abstract

#close, #cp, #mv, #read, #write

Constructor Details

#initialize(**opts) ⇒ InMem

Returns a new instance of InMem.



10
11
12
13
# File 'lib/bfs/bucket/in_mem.rb', line 10

def initialize(**opts)
  super(**opts.dup)
  @files = {}
end

Instance Method Details

#clearObject

Reset bucket and clear all files.



16
17
18
# File 'lib/bfs/bucket/in_mem.rb', line 16

def clear
  @files.clear
end

#create(path, encoding: self.encoding, content_type: nil, metadata: nil, **_opts, &block) ⇒ Object

Creates a new file and opens it for writing.

Parameters:

  • path (String)

    The creation path.

  • opts (Hash)

    Additional options.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/bfs/bucket/in_mem.rb', line 45

def create(path, encoding: self.encoding, content_type: nil, metadata: nil, **_opts, &block)
  io = StringIO.new
  io.set_encoding(encoding)

  entry = Entry.new(io, Time.now, content_type, norm_meta())
  @files[norm_path(path)] = entry
  return io unless block

  begin
    yield(io)
  ensure
    io.close
  end
end

#info(path, **_opts) ⇒ Object

Info returns the file info

Raises:



30
31
32
33
34
35
36
# File 'lib/bfs/bucket/in_mem.rb', line 30

def info(path, **_opts)
  path = norm_path(path)
  raise BFS::FileNotFound, path unless @files.key?(path)

  entry = @files[path]
  BFS::FileInfo.new(path: path, size: entry.io.size, mtime: entry.mtime, content_type: entry.content_type, metadata: entry.)
end

#ls(pattern = '**/*', **_opts) ⇒ Object

Lists the contents of a bucket using a glob pattern



21
22
23
24
25
26
27
# File 'lib/bfs/bucket/in_mem.rb', line 21

def ls(pattern = '**/*', **_opts)
  Enumerator.new do |y|
    @files.each_key do |key|
      y << key if File.fnmatch?(pattern, key, File::FNM_PATHNAME)
    end
  end
end

#open(path, **_opts, &block) ⇒ Object

Opens an existing file for reading

Raises:



61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/bfs/bucket/in_mem.rb', line 61

def open(path, **_opts, &block)
  path = norm_path(path)
  raise BFS::FileNotFound, path unless @files.key?(path)

  io = @files[path].io
  io.reopen(io.string)
  return io unless block

  begin
    yield(io)
  ensure
    io.close
  end
end

#rm(path, **_opts) ⇒ Object

Deletes a file.



77
78
79
# File 'lib/bfs/bucket/in_mem.rb', line 77

def rm(path, **_opts)
  @files.delete(norm_path(path))
end