Class: Protocol::HTTP::Body::File

Inherits:
Readable
  • Object
show all
Defined in:
lib/protocol/http/body/file.rb

Constant Summary collapse

BLOCK_SIZE =
Async::IO::BLOCK_SIZE
MODE =
::File::RDONLY | ::File::BINARY

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Readable

#each, #finish

Constructor Details

#initialize(file, range = nil, size: file.size, block_size: BLOCK_SIZE) ⇒ File

Returns a new instance of File.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/protocol/http/body/file.rb', line 37

def initialize(file, range = nil, size: file.size, block_size: BLOCK_SIZE)
  @file = file
  
  @block_size = block_size
  
  if range
    @file.seek(range.min)
    @offset = range.min
    @length = @remaining = range.size
  else
    @offset = 0
    @length = @remaining = size
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



59
60
61
# File 'lib/protocol/http/body/file.rb', line 59

def file
  @file
end

#lengthObject (readonly)

Returns the value of attribute length.



62
63
64
# File 'lib/protocol/http/body/file.rb', line 62

def length
  @length
end

#offsetObject (readonly)

Returns the value of attribute offset.



61
62
63
# File 'lib/protocol/http/body/file.rb', line 61

def offset
  @offset
end

Class Method Details

.open(path, *arguments, **options) ⇒ Object



33
34
35
# File 'lib/protocol/http/body/file.rb', line 33

def self.open(path, *arguments, **options)
  self.new(::File.open(path, MODE), *arguments, **options)
end

Instance Method Details

#close(error = nil) ⇒ Object



52
53
54
55
56
57
# File 'lib/protocol/http/body/file.rb', line 52

def close(error = nil)
  @file.close
  @remaining = 0
  
  super
end

#empty?Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/protocol/http/body/file.rb', line 64

def empty?
  @remaining == 0
end

#inspectObject



94
95
96
# File 'lib/protocol/http/body/file.rb', line 94

def inspect
  "\#<#{self.class} file=#{@file.inspect} offset=#{@offset} remaining=#{@remaining}>"
end

#joinObject



84
85
86
87
88
89
90
91
92
# File 'lib/protocol/http/body/file.rb', line 84

def join
  return "" if @remaining == 0
  
  buffer = @file.read(@remaining)
  
  @remaining = 0
  
  return buffer
end

#readObject



72
73
74
75
76
77
78
79
80
81
82
# File 'lib/protocol/http/body/file.rb', line 72

def read
  if @remaining > 0
    amount = [@remaining, @block_size].min
    
    if chunk = @file.read(amount)
      @remaining -= chunk.bytesize
      
      return chunk
    end
  end
end

#rewindObject



68
69
70
# File 'lib/protocol/http/body/file.rb', line 68

def rewind
  @file.seek(@offset)
end