Class: Increase::FileUpload

Inherits:
Object
  • Object
show all
Defined in:
lib/increase/file_upload.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_or_path, filename: nil, content_type: nil) ⇒ FileUpload

Returns a new instance of FileUpload.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/increase/file_upload.rb', line 12

def initialize(file_or_path, filename: nil, content_type: nil)
  @filename = filename
  @content_type = content_type

  if file_or_path.is_a?(File) || file_or_path.is_a?(Tempfile)
    @file = file_or_path
    @filename ||= File.basename(file_or_path.path)
  elsif file_or_path.is_a?(String)
    # Treat string as a filepath
    @file = File.open(file_or_path)
    @filename ||= File.basename(file_or_path)
  elsif file_or_path.respond_to?(:read)
    @file = Tempfile.new(default_filename)
    @file.write(file_or_path.read)
  else
    raise ArgumentError, "File or path required"
  end

  # Try to guess content type
  @content_type ||= Marcel::MimeType.for(@file, name: @filename)
  @filename ||= default_filename
end

Instance Attribute Details

#content_typeObject (readonly)

Returns the value of attribute content_type.



10
11
12
# File 'lib/increase/file_upload.rb', line 10

def content_type
  @content_type
end

#fileObject (readonly)

Returns the value of attribute file.



10
11
12
# File 'lib/increase/file_upload.rb', line 10

def file
  @file
end

#filenameObject (readonly)

Returns the value of attribute filename.



10
11
12
# File 'lib/increase/file_upload.rb', line 10

def filename
  @filename
end

Instance Method Details

#file_partObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/increase/file_upload.rb', line 35

def file_part
  if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new("2.0")
    Faraday::Multipart::FilePart.new(
      @file,
      @content_type,
      @filename
    )
  else
    Faraday::FilePart.new(
      @file,
      @content_type,
      @filename
    )
  end
end