Class: Planter::CsvDataSource

Inherits:
Object
  • Object
show all
Defined in:
lib/planter/csv_data_source.rb

Overview

Loads CSV seed data for a configured seeder.

Instance Method Summary collapse

Constructor Details

#initialize(context:, seeder:) ⇒ CsvDataSource

Create a CSV data source.

Parameters:



13
14
15
16
# File 'lib/planter/csv_data_source.rb', line 13

def initialize(context:, seeder:)
  @context = context
  @seeder = seeder
end

Instance Method Details

#dataArray<Hash>

Return parsed CSV rows as hashes.

Returns:

  • (Array<Hash>)


22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/planter/csv_data_source.rb', line 22

def data
  contents = ::File.read(path)
  if path.include?(".erb")
    contents = ERB.new(contents, trim_mode: context.erb_trim_mode).result(seeder_binding)
  end

  ::CSV.parse(
    contents,
    headers: true,
    header_converters: :symbol
  ).map(&:to_hash)
end

#pathString?

Return the first matching CSV path for the configured CSV name.

Returns:

  • (String, nil)


39
40
41
42
43
44
# File 'lib/planter/csv_data_source.rb', line 39

def path
  @path ||=
    %W[#{context.csv_name}.csv #{context.csv_name}.csv.erb #{context.csv_name}.erb.csv]
      .map { |file| Rails.root.join(Planter.config.csv_files_directory, file).to_s }
      .find { |file| ::File.file?(file) }
end