Class: Async::HTTP::Body::File

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

Constant Summary collapse

BLOCK_SIZE =
Async::IO::Stream::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, block_size: BLOCK_SIZE) ⇒ File

Returns a new instance of File.



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

def initialize(file, range = nil, 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 = @file.size
  end
end

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file.



57
58
59
# File 'lib/async/http/body/file.rb', line 57

def file
  @file
end

#lengthObject (readonly)

Returns the value of attribute length.



60
61
62
# File 'lib/async/http/body/file.rb', line 60

def length
  @length
end

#offsetObject (readonly)

Returns the value of attribute offset.



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

def offset
  @offset
end

Class Method Details

.open(path, *args) ⇒ Object



31
32
33
# File 'lib/async/http/body/file.rb', line 31

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

Instance Method Details

#close(error = nil) ⇒ Object



50
51
52
53
54
55
# File 'lib/async/http/body/file.rb', line 50

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

#empty?Boolean

Returns:

  • (Boolean)


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

def empty?
  @remaining == 0
end

#inspectObject



92
93
94
# File 'lib/async/http/body/file.rb', line 92

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

#joinObject



82
83
84
85
86
87
88
89
90
# File 'lib/async/http/body/file.rb', line 82

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

#readObject



70
71
72
73
74
75
76
77
78
79
80
# File 'lib/async/http/body/file.rb', line 70

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

#rewindObject



66
67
68
# File 'lib/async/http/body/file.rb', line 66

def rewind
  @file.seek(@offset)
end