class Faraday::Response::ParseCSV

Parses response bodies as CSV

@example

require 'faraday/csv'

connection = Faraday.new('https://example.org/') do |faraday|
  faraday.response :csv, headers: :first_row
  faraday.adapter Faraday.default_adapter
end

response = connection.get('/data.csv')
response.body.first #=> <CSV::Row "foo":"bar">

@api private

Constants

CSV_CONTENT_TYPE_RE
TARGET_ENCODING

Attributes

opts[R]

Public Class Methods

new(app = nil, opts = {}) click to toggle source

Creates a new instance of CSV parsing middleware

@param app [#call, nil] Rack app @param opts [Hash] CSV parsing options @see CSV.new

Calls superclass method
# File lib/faraday/response/parse_csv.rb, line 33
def initialize(app = nil, opts = {})
  @opts = opts

  super(app)
end

Private Instance Methods

on_complete(env) click to toggle source
# File lib/faraday/response/parse_csv.rb, line 55
def on_complete(env) # rubocop:disable MethodLength,AbcSize
  return unless env.parse_body?

  content_type = env.response_headers[:content_type]
  csv_content_type = content_type.match(CSV_CONTENT_TYPE_RE)

  return unless csv_content_type

  charset = csv_content_type[:charset]
  env.body.encode!(TARGET_ENCODING, charset) if charset

  env.body = CSV.parse(env.body, opts)
rescue ::EncodingError => error
  raise Faraday::EncodingError.new(error, env.response)
rescue CSV::MalformedCSVError => error
  raise Faraday::ParsingError.new(error, env.response)
end