Method: ApimaticCalculator::APIHelper.form_encode

Defined in:
lib/apimatic_calculator/api_helper.rb

.form_encode(obj, instance_name, formatting: 'indexed') ⇒ Hash

Form encodes an object. of a hash.

Parameters:

  • An (Dynamic)

    object to form encode.

  • The (String)

    name of the object.

Returns:

  • (Hash)

    A form encoded representation of the object in the form



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/apimatic_calculator/api_helper.rb', line 206

def self.form_encode(obj, instance_name, formatting: 'indexed')
  retval = {}

  serializable_types = [String, Numeric, TrueClass,
                        FalseClass, Date, DateTime]

  # If this is a structure, resolve it's field names.

  obj = obj.to_hash if obj.is_a? BaseModel

  # Create a form encoded hash for this object.

  if obj.nil?
    nil
  elsif obj.instance_of? Array
    if formatting == 'indexed'
      obj.each_with_index do |value, index|
        retval.merge!(APIHelper.form_encode(value, "#{instance_name}[#{index}]"))
      end
    elsif serializable_types.map { |x| obj[0].is_a? x }.any?
      obj.each do |value|
        abc = if formatting == 'unindexed'
                APIHelper.form_encode(value, "#{instance_name}[]",
                                      formatting: formatting)
              else
                APIHelper.form_encode(value, instance_name,
                                      formatting: formatting)
              end
        retval = APIHelper.custom_merge(retval, abc)
      end
    else
      obj.each_with_index do |value, index|
        retval.merge!(APIHelper.form_encode(value, "#{instance_name}[#{index}]",
                                            formatting: formatting))
      end
    end
  elsif obj.instance_of? Hash
    obj.each do |key, value|
      retval.merge!(APIHelper.form_encode(value, "#{instance_name}[#{key}]",
                                          formatting: formatting))
    end
  elsif obj.instance_of? File
    retval[instance_name] = UploadIO.new(
      obj, 'application/octet-stream', File.basename(obj.path)
    )
  else
    retval[instance_name] = obj
  end
  retval
end