Module: IGMarkets::RequestBodyFormatter

Defined in:
lib/ig_markets/request_body_formatter.rb

Overview

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

Class Method Summary collapse

Class Method Details

.format(model, defaults = {}) ⇒ Hash

Takes a Model and returns its attributes in a hash ready to be passed as a request body to the IG Markets API. Attribute names will be converted from snake case to camel 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 first available `:format` option.

Parameters:

  • model (Model)

    The model instance to convert attributes for.

  • defaults (Hash) (defaults to: {})

    The default attribute values to return, can be overridden by values set on ‘model`.

Returns:

  • (Hash)

    The resulting attributes hash.



17
18
19
20
21
22
23
24
25
# File 'lib/ig_markets/request_body_formatter.rb', line 17

def format(model, defaults = {})
  model.class.defined_attributes.each_with_object(defaults.dup) 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)


33
34
35
36
37
38
39
40
41
# File 'lib/ig_markets/request_body_formatter.rb', line 33

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

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

  return value.strftime(Array(options.fetch(:format)).first) 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)


48
49
50
51
52
# File 'lib/ig_markets/request_body_formatter.rb', line 48

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

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