Sha256: b57c41f32019ab87f74283d9cc0119c0955e01cb143b7091cd7718db9f66d7e8

Contents?: true

Size: 1.35 KB

Versions: 48

Compression:

Stored size: 1.35 KB

Contents

# Acts as a proxy to turn ActiveStorage file into IO object

module FormatParser
  module ActiveStorage
    class BlobIO
      # @param blob[ActiveStorage::Blob] the file with linked service
      # @return [BlobIO]
      def initialize(blob)
        @blob = blob
        @service = blob.service
        @pos = 0
      end

      # Emulates IO#read, but requires the number of bytes to read.
      # Rely on `ActiveStorage::Service.download_chunk` of each hosting type (local, S3, Azure, etc)
      #
      # @param n_bytes[Integer] how many bytes to read
      # @return [String] the read bytes
      def read(n_bytes)
        # HTTP ranges are exclusive.
        http_range = (@pos..(@pos + n_bytes - 1))
        body = @service.download_chunk(@blob.key, http_range)
        @pos += body.bytesize
        body.force_encoding(Encoding::ASCII_8BIT)
      end

      # Emulates IO#seek
      #
      # @param [Integer] offset size
      # @return [Integer] always return 0, `seek` only mutates `pos` attribute
      def seek(offset)
        @pos = offset
        0
      end

      # Emulates IO#size.
      #
      # @return [Integer] the size of the blob size from ActiveStorage
      def size
        @blob.byte_size
      end

      # Emulates IO#pos
      #
      # @return [Integer] the current offset (in bytes) of the io
      def pos
        @pos
      end
    end
  end
end

Version data entries

48 entries across 48 versions & 1 rubygems

Version Path
format_parser-2.10.0 lib/active_storage/blob_io.rb
format_parser-2.9.0 lib/active_storage/blob_io.rb
format_parser-2.8.0 lib/active_storage/blob_io.rb
format_parser-2.7.2 lib/active_storage/blob_io.rb
format_parser-2.7.1 lib/active_storage/blob_io.rb
format_parser-2.7.0 lib/active_storage/blob_io.rb
format_parser-2.6.0 lib/active_storage/blob_io.rb
format_parser-2.5.0 lib/active_storage/blob_io.rb
format_parser-2.4.5 lib/active_storage/blob_io.rb
format_parser-2.4.4 lib/active_storage/blob_io.rb
format_parser-2.4.3 lib/active_storage/blob_io.rb
format_parser-2.3.0 lib/active_storage/blob_io.rb
format_parser-2.2.1 lib/active_storage/blob_io.rb
format_parser-2.2.0 lib/active_storage/blob_io.rb
format_parser-2.1.0 lib/active_storage/blob_io.rb
format_parser-2.0.0 lib/active_storage/blob_io.rb
format_parser-2.0.0.pre.4 lib/active_storage/blob_io.rb
format_parser-2.0.0.pre.3 lib/active_storage/blob_io.rb
format_parser-2.0.0.pre.2 lib/active_storage/blob_io.rb
format_parser-2.0.0.pre lib/active_storage/blob_io.rb