Class: Common::Client::Middleware::Response::Snakecase

Inherits:
Faraday::Middleware
  • Object
show all
Defined in:
lib/common/client/middleware/response/snakecase.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = { symbolize: true }) ⇒ Snakecase

Returns a new instance of Snakecase.



8
9
10
11
# File 'lib/common/client/middleware/response/snakecase.rb', line 8

def initialize(app, options = { symbolize: true })
  super(app)
  @symbolize = options[:symbolize]
end

Instance Method Details

#deserialized_body?(body) ⇒ Boolean (private)

Returns:

  • (Boolean)


31
32
33
# File 'lib/common/client/middleware/response/snakecase.rb', line 31

def deserialized_body?(body)
  body.is_a?(Array) || body.is_a?(Hash)
end

#on_complete(env) ⇒ Object



13
14
15
16
17
18
# File 'lib/common/client/middleware/response/snakecase.rb', line 13

def on_complete(env)
  # return false unless env.response_headers['content-type'] =~ /\b(xml|json)/
  return unless deserialized_body?(env.body)

  env.body = parse(env.body)
end

#parse(parsed_object) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/common/client/middleware/response/snakecase.rb', line 20

def parse(parsed_object)
  case parsed_object
  when Array
    parsed_object.map { |hash| transform(hash) }
  when Hash
    transform(parsed_object)
  end
end

#transform(hash) ⇒ Object (private)



35
36
37
38
39
40
41
# File 'lib/common/client/middleware/response/snakecase.rb', line 35

def transform(hash)
  if @symbolize
    hash.deep_transform_keys { |k| k.underscore.to_sym }
  else
    hash.deep_transform_keys(&:underscore)
  end
end