Class: Racknga::Middleware::Range::RangeStream — racknga - Ranguba

Class: Racknga::Middleware::Range::RangeStream

Inherits:
Object
  • Object
show all
Defined in:
lib/racknga/middleware/range.rb

Instance Method Summary (collapse)

Constructor Details

- (RangeStream) initialize(body, first_byte, length)

A new instance of RangeStream



123
124
125
126
127
# File 'lib/racknga/middleware/range.rb', line 123

def initialize(body, first_byte, length)
  @body = body
  @first_byte = first_byte
  @length = length
end

Instance Method Details

- (Object) each



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/racknga/middleware/range.rb', line 129

def each
  if @body.respond_to?(:seek)
    @body.seek(@first_byte)
    start = 0
  else
    start = @first_byte
  end
  rest = @length

  @body.each do |chunk|
    if chunk.respond_to?(:encoding)
      if chunk.encoding != Encoding::ASCII_8BIT
        chunk = chunk.dup.force_encoding(Encoding::ASCII_8BIT)
      end
    end

    chunk_size = chunk.size
    if start > 0
      if chunk_size < start
        start -= chunk_size
        next
      else
        chunk = chunk[start..-1]
        chunk_size -= start
        start = 0
      end
    end
    if rest > chunk_size
      yield(chunk)
      rest -= chunk_size
    else
      yield(chunk[0, rest])
      rest -= rest
    end
    break if rest <= 0
  end
end