Class: Carrierwave::Base64::Base64StringIO

Inherits:
StringIO
  • Object
show all
Defined in:
lib/carrierwave/base64/base64_string_io.rb

Overview

Class that decodes a base64 string, builds a StringIO for the decoded bytes, and extracts the file MIME type to build a file name with extension.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(encoded_file, file_name) ⇒ StringIO

Returns a StringIO with decoded bytes from the base64 encoded string and builds a file name with extension for the uploaded file, based on the MIME type specified in the base64 encoded string.

Parameters:

  • encoded_file (String)

    the base64 encoded file contents

  • file_name (String)

    the file name without extention

Raises:

  • (ArgumentError)

    If the base64 encoded string is empty


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/carrierwave/base64/base64_string_io.rb', line 23

def initialize(encoded_file, file_name)
  description, encoded_bytes = encoded_file.split(',')

  raise ArgumentError unless encoded_bytes
  raise ArgumentError if encoded_bytes.eql?('(null)')

  @file_name = file_name
  @file_extension = get_file_extension description
  bytes = ::Base64.decode64 encoded_bytes

  super bytes
end

Instance Attribute Details

#file_extensionString (readonly)

Returns the file extension for the uploaded file

Returns:

  • (String)

    the file extension for the uploaded file


11
12
13
# File 'lib/carrierwave/base64/base64_string_io.rb', line 11

def file_extension
  @file_extension
end

#file_nameString (readonly)

Returns the file name without extension

Returns:

  • (String)

    the file name without extension


8
9
10
# File 'lib/carrierwave/base64/base64_string_io.rb', line 8

def file_name
  @file_name
end

Instance Method Details

#original_filenameString

Returns a file name with extension, based on the MIME type specified in the base64 encoded string.

Returns:

  • (String)

    File name with extention


40
41
42
# File 'lib/carrierwave/base64/base64_string_io.rb', line 40

def original_filename
  File.basename("#{@file_name}.#{@file_extension}")
end