Class: Lutaml::Lml::Executor::CsvAdapter

Inherits:
Object
  • Object
show all
Extended by:
AdapterHelpers
Defined in:
lib/lutaml/lml/executor/csv_adapter.rb

Overview

CSV format adapter. Reads CSV files and maps rows to hydrated compiled-class instances using column mappings from the import definition. Exports instances back to CSV.

Registered for format “csv” via FormatAdapter::BUILTIN_ADAPTERS.

Class Method Summary collapse

Methods included from AdapterHelpers

attribute_value, find_attribute, find_class_for_instance, resolve_target_class

Class Method Details

.export(exp, instances, compiled:) ⇒ Object

Write instances to a CSV file.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/lutaml/lml/executor/csv_adapter.rb', line 37

def self.export(exp, instances, compiled:)
  return if instances.empty?

  path = attribute_value(exp.attributes, "file")
  return unless path && !path.empty?

  first_instance = instances.first
  class_name, target_class = find_class_for_instance(first_instance, compiled)
  return unless target_class

  fields = target_class.attributes.keys
  rows = instances.map do |inst|
    fields.map { |f| extract_attribute_value(inst, f) }
  end

  File.write(path, generate_csv(fields, rows))
end

.import(imp, compiled:) ⇒ Object

Read a CSV file and map rows to compiled-class instances. Returns an array of hydrated objects.

The import definition’s attributes provide column mappings:

attribute name = "csv_column_header"


21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/lutaml/lml/executor/csv_adapter.rb', line 21

def self.import(imp, compiled:)
  return [] unless imp.file
  return [] unless imp.attributes&.any?

  mappings = build_column_mappings(imp.attributes)
  target_class = resolve_target_class(imp.attributes, compiled)
  return [] unless target_class

  path = imp.file
  return [] unless File.exist?(path)

  rows = CSV.read(path, headers: true)
  rows.map { |row| build_instance(row, mappings, target_class) }
end