Module: Http::Multipart

Defined in:
lib/angus/remote/http/multipart.rb

Constant Summary collapse

TRANSFORMABLE_TYPES =
[File, Tempfile, StringIO]
QUERY_STRING_NORMALIZER =
Proc.new do |params|
  Multipart.flatten_params(params).map do |(k,v)|
    [k, Multipart.transformable_type?(v) ? Multipart.file_to_upload_io(v) : v]
  end
end

Class Method Summary collapse

Class Method Details

.file_to_upload_io(file) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/angus/remote/http/multipart.rb', line 15

def self.file_to_upload_io(file)
  if file.respond_to? :original_filename
    filename = file.original_filename
  else
    filename =  File.split(file.path).last
  end
  content_type = 'application/octet-stream'
  UploadIO.new(file, content_type, filename)
end

.flatten_params(params = {}, prefix = '') ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/angus/remote/http/multipart.rb', line 35

def self.flatten_params(params={}, prefix='')
  flattened = []
  params.each do |(k,v)|
    if params.is_a?(Array)
      v = k
      k = ''
    end

    flattened_key = prefix == '' ? "#{k}" : "#{prefix}[#{k}]"
    if v.is_a?(Hash) || v.is_a?(Array)
      flattened += flatten_params(v, flattened_key)
    else
      flattened << [flattened_key, v]
    end
  end
  flattened
end

.hash_contains_files?(hash) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/angus/remote/http/multipart.rb', line 25

def self.hash_contains_files?(hash)
  hash.is_a?(Hash) && self.flatten_params(hash).select do |(k,v)|
    self.transformable_type?(v) || v.is_a?(UploadIO)
  end.size > 0
end

.transformable_type?(object) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/angus/remote/http/multipart.rb', line 31

def self.transformable_type?(object)
  TRANSFORMABLE_TYPES.any? { |klass| object.is_a?(klass) }
end