Module: Sequel::Plugins::CsvSerializer::ClassMethods

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#csv_serializer_optsObject (readonly)

The default opts to use when serializing model objects to CSV


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

def csv_serializer_opts
  @csv_serializer_opts
end

Instance Method Details

#array_from_csv(csv, opts = OPTS) ⇒ Object

Attempt to parse an array of instances from the given CSV string


83
84
85
86
87
88
89
# File 'lib/sequel/plugins/csv_serializer.rb', line 83

def array_from_csv(csv, opts = OPTS)
  CSV.parse(csv, process_csv_serializer_opts(opts)).map do |row|
    row = row.to_hash
    row.delete(nil)
    new(row)
  end
end

#freezeObject

Freeze csv serializier opts when freezing model class


92
93
94
95
96
97
98
# File 'lib/sequel/plugins/csv_serializer.rb', line 92

def freeze
  @csv_serializer_opts.freeze.each_value do |v|
    v.freeze if v.is_a?(Array) || v.is_a?(Hash)
  end

  super
end

#from_csv(csv, opts = OPTS) ⇒ Object

Attempt to parse a single instance from the given CSV string


101
102
103
# File 'lib/sequel/plugins/csv_serializer.rb', line 101

def from_csv(csv, opts = OPTS)
  new.from_csv(csv, opts)
end

#process_csv_serializer_opts(opts) ⇒ Object

Convert the options hash to one that can be passed to CSV.


106
107
108
109
110
111
112
113
# File 'lib/sequel/plugins/csv_serializer.rb', line 106

def process_csv_serializer_opts(opts)
  opts = (csv_serializer_opts || OPTS).merge(opts)
  opts_cols = opts.delete(:columns)
  opts_include = opts.delete(:include)
  opts_except = opts.delete(:except)
  opts[:headers] ||= Array(opts.delete(:only) || opts_cols || columns) + Array(opts_include) - Array(opts_except)
  opts
end