See more posts

Automatic object creation when deserializing CSV

Ruby is a great language, but also has a rich standard library. It's fun to find these kinds of tricks when you're working on a project.

https://ruby-doc.org/stdlib-3.0.0/libdoc/csv/rdoc/CSV.html#class-CSV-label-Field+Converters

ruby
require "csv"

class Car
  def initialize(make, model)
    @make = make
    @model = model
  end
end

car_converter = ->(value, field_info) do
  if field_info.header == "car"
    Car.new(*value.split(/\s*,\s*/))
  else
    value
  end
end

csv_data = CSV.parse(<<~CSV, headers: true, converters: [car_converter])
  person,car
  Alex,"Volkswagen, Jetta"
CSV

puts csv_data.to_h.inspect
text
# => {["person", "Alex"]=>["car", #<Car:0x00007fdf4d80f7f8 @make="Volkswagen", @model="Jetta">]}

Thanks for reading! See more posts Leave feedback