Module: IGMarkets::PayloadFormatter

Defined in:
lib/ig_markets/payload_formatter.rb

Overview

Contains methods for formatting payloads that can be passed to the IG Markets API.

Class Method Summary collapse

Class Method Details

.format(model) ⇒ Hash

Takes a Model and returns its attributes in a hash ready to be passed as a payload to the IG Markets API. Attribute names will be converted to use camel case rather than snake case, Symbol attributes will be converted to strings and will be uppercased, and both Date and Time attributes will be converted to strings using their ‘:format’ option.

Parameters:

  • model (Model)

    The model instance to convert attributes for.

Returns:

  • (Hash)

    The resulting attributes hash.



14
15
16
17
18
19
20
21
22
# File 'lib/ig_markets/payload_formatter.rb', line 14

def format(model)
  model.class.defined_attributes.each_with_object({}) do |(name, options), formatted|
    value = model.send name

    next if value.nil?

    formatted[snake_case_to_camel_case(name)] = format_value value, options
  end
end

.format_value(value, options) ⇒ String

Formats an individual value, see #format for details.

Parameters:

  • value

    The attribute value to format.

  • options

    The options hash for the attribute.

Returns:

  • (String)


30
31
32
33
34
35
36
37
38
# File 'lib/ig_markets/payload_formatter.rb', line 30

def format_value(value, options)
  return value.to_s.upcase if options[:type] == Symbol

  value = value.utc if options[:type] == Time

  return value.strftime(options.fetch(:format)) if [Date, Time].include? options[:type]

  value
end

.snake_case_to_camel_case(value) ⇒ Symbol

Takes a string or symbol that uses snake case and converts it to a camel case symbol.

Parameters:

  • value (String, Symbol)

    The string or symbol to convert to camel case.

Returns:

  • (Symbol)


45
46
47
48
49
# File 'lib/ig_markets/payload_formatter.rb', line 45

def snake_case_to_camel_case(value)
  pieces = value.to_s.split '_'

  (pieces[0] + pieces[1..-1].map(&:capitalize).join).to_sym
end