Module: Sequel::Plugins::CsvSerializer

Defined in:
lib/sequel/plugins/csv_serializer.rb

Overview

csv_serializer handles serializing entire Sequel::Model objects to CSV, as well as support for deserializing CSV directly into Sequel::Model objects. It requires either the csv standard library when usnig ruby 1.9+, or the fastercsv gem when using ruby 1.8.

Basic Example:

album = Album[1]
album.to_csv(:write_headers=>true)
# => "id,name,artist_id\n1,RF,2\n"

You can provide options to control the CSV output:

album.to_csv(:only=>:name)
album.to_csv(:except=>[:id, :artist_id])
# => "RF\n"

to_csv also exists as a class and dataset method, both of which return all objects in the dataset:

Album.to_csv
Album.filter(:artist_id=>1).to_csv

If you have an existing array of model instance you want to convert to CSV, you can call the class to_csv method with the :array option:

Album.to_csv(:array=>[Album[1], Album[2]])

In addition to creating CSV, this plugin also enables Sequel::Model classes to create instances directly from CSV using the from_csv class method:

csv = album.to_csv
album = Album.from_csv(csv)

The array_from_csv class method exists to parse arrays of model instances from CSV:

csv = Album.filter(:artist_id=>1).to_csv
albums = Album.array_from_csv(csv)

These do not necessarily round trip, since doing so would let users create model objects with arbitrary values. By default, from_csv will call set with the values in the hash. If you want to specify the allowed fields, you can use the :headers option.

Album.from_csv(album.to_csv, :headers=>%w'id name')

If you want to update an existing instance, you can use the from_csv instance method:

album.from_csv(csv)

Usage:

# Add CSV output capability to all model subclass instances (called
# before loading subclasses)
Sequel::Model.plugin :csv_serializer

# Add CSV output capability to Album class instances
Album.plugin :csv_serializer

Defined Under Namespace

Modules: ClassMethods, DatasetMethods, InstanceMethods

Constant Summary collapse

CSV =
Object.const_defined?(:CSV) ? ::CSV : ::FasterCSV

Class Method Summary collapse

Class Method Details

.configure(model, opts = {}) ⇒ Object

Set up the column readers to do deserialization and the column writers to save the value in deserialized_values



79
80
81
82
83
# File 'lib/sequel/plugins/csv_serializer.rb', line 79

def self.configure(model, opts = {})
  model.instance_eval do
    @csv_serializer_opts = (@csv_serializer_opts || {}).merge(opts)
  end
end