class SimpleHelper::ResponseParser

Constants

UTF8_BOM

TODO: Support other formats like xml

Attributes

body[R]
format[R]
path[R]

Public Class Methods

new(body, format, path) click to toggle source
# File lib/simple_helper/response_parser.rb, line 11
def initialize(body, format, path)
  @body = body
  @format = format
  @path = path
end
perform(body, format, path) click to toggle source
# File lib/simple_helper/response_parser.rb, line 17
def self.perform(body, format, path)
  new(body, format, path).parse
end

Public Instance Methods

parse() click to toggle source
# File lib/simple_helper/response_parser.rb, line 21
def parse
  return nil if body.nil?
  return nil if body == 'null'
  return nil if body.valid_encoding? && body.strip.empty?

  @body = body.gsub(/\A#{UTF8_BOM}/, '') if body.valid_encoding? && body.encoding == Encoding::UTF_8
  send(format)
end

Protected Instance Methods

csv() click to toggle source
# File lib/simple_helper/response_parser.rb, line 46
def csv
  data = path.nil? ? json : json.dig(*path.split(','))
  raise ArgumentError, 'Cannot export nil or empty hash please pass proper path'.bold.brown.gray if data.nil?

  Array.wrap(data).to_csv('file_name.csv')
end
json() click to toggle source
# File lib/simple_helper/response_parser.rb, line 36
def json
  JSON.parse(body, quirks_mode: true, allow_nan: true)
rescue JSON::ParserError
  puts "Response cannot be parsed because it's not a string nor valid JSON. please use .plain to get the the plain response".bold.brown.gray
end
plain() click to toggle source
# File lib/simple_helper/response_parser.rb, line 42
def plain
  body
end