Class: SpeakyCsv::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/speaky_csv/base.rb

Overview

Inherit from this class when using SpeakyCsv

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.define_csv_fields {|csv_field_builder| ... } ⇒ Object

Yields:

  • (csv_field_builder)


71
72
73
74
# File 'lib/speaky_csv/base.rb', line 71

def self.define_csv_fields
  self.csv_field_builder = csv_field_builder.deep_dup
  yield csv_field_builder
end

.exporter(records_enumerator) ⇒ Object

Return a new exporter instance



77
78
79
80
# File 'lib/speaky_csv/base.rb', line 77

def self.exporter(records_enumerator)
  Export.new csv_field_builder,
             records_enumerator
end

Instance Method Details

#active_record_importer(input_io_or_enumerable, klass) ⇒ Object

Return a new active record instance from the given IO, which is expected to be able to read a csv file. The importer will be an Enumerator that returns successive active records.

For example:

class UserCsv < SpeakyCsv::Base

define_csv_fields do |c|
  c.fields :id, :name
end

end

File.open(‘sample.csv’, ‘r’) do |io|

importer = SomeFormat.new.active_record_importer io, User

importer.each do |record|
  # record will be a User instance or nil
end

end

Optionally an Enumerable instance can be passed instead of an IO instance. The enumerable should return attr hashes. This may be helpful for transforming or chaining Enumerables.



128
129
130
131
132
133
# File 'lib/speaky_csv/base.rb', line 128

def active_record_importer(input_io_or_enumerable, klass)
  ActiveRecordImport.new \
    self.class.csv_field_builder,
    input_io_or_enumerable,
    klass
end

#attr_importer(input_io) ⇒ Object

Return a new attr importer instance from the given IO, which is expected to be able to read a csv file. The importer will be an Enumerator that returns successive attribute hashes.

For example:

class SomeFormat < SpeakyCsv::Base

define_csv_fields do |c|
  c.fields :id, :name
end

end

File.open(‘sample.csv’, ‘r’) do |io|

importer = SomeFormat.new.attr_importer io

importer.each do |attrs|
  # attrs will be hashes like { "id" => 123, "name" => "Curley" }
end

end



101
102
103
104
# File 'lib/speaky_csv/base.rb', line 101

def attr_importer(input_io)
  AttrImport.new self.class.csv_field_builder,
                 input_io
end