Delimit.Writer (delimit v0.2.0)

View Source

Functions for writing delimited data to files or strings.

This module provides functionality to write delimited data to files or strings based on schema definitions, supporting both single-write and streaming operations.

Summary

Types

Options for writing delimited data.

Functions

Streams delimited data to a file.

Writes delimited data to a file.

Writes delimited data to a string.

Types

write_options()

@type write_options() :: [
  delimiter: String.t(),
  escape: String.t(),
  line_ending: String.t(),
  format: atom()
]

Options for writing delimited data.

  • :delimiter - The field delimiter character (default: comma)
  • :escape - The escape character used for quotes (default: double-quote)
  • :line_ending - Line ending to use (default: system-dependent)
  • :format - Predefined format (:csv, :tsv, :psv) that sets appropriate options

Functions

stream_to_file(schema, path, data_stream, opts \\ [])

@spec stream_to_file(Delimit.Schema.t(), Path.t(), Enumerable.t(), write_options()) ::
  :ok

Streams delimited data to a file.

Parameters

  • schema - The schema definition
  • path - Path to the output file
  • data_stream - Stream of structs to write
  • opts - Write options that override schema options

Returns

  • :ok on success

Example

iex> stream = Stream.map(1..1000, fn i -> %MyApp.Person{first_name: "User", last_name: "User", age: i} end)
iex> MyApp.Person.stream_to_file("people.csv", stream)
:ok

iex> stream = Stream.map(1..1000, fn i -> %MyApp.Person{first_name: "User", last_name: "User", age: i} end)
iex> MyApp.Person.stream_to_file("people.tsv", stream, format: :tsv)
:ok

write_file(schema, path, data, opts \\ [])

@spec write_file(Delimit.Schema.t(), Path.t(), [struct()], write_options()) :: :ok

Writes delimited data to a file.

Parameters

  • schema - The schema definition
  • path - Path to the output file
  • data - List of structs to write
  • opts - Write options that override schema options

Returns

  • :ok on success

Example

iex> people = [%MyApp.Person{first_name: "John", last_name: "Doe", age: 42}]
iex> MyApp.Person.write("people.csv", people)
:ok

write_string(schema, data, opts \\ [])

@spec write_string(Delimit.Schema.t(), [struct()], write_options()) :: binary()

Writes delimited data to a string.

Parameters

  • schema - The schema definition
  • data - List of structs to write
  • opts - Write options that override schema options

Returns

  • String containing the delimited data

Example

iex> people = [%MyApp.Person{first_name: "John", last_name: "Doe", age: 42}]
iex> MyApp.Person.write_string(people)
"first_name,last_name,age\nJohn,Doe,42\n"

iex> people = [%MyApp.Person{first_name: "John", last_name: "Doe", age: 42}]
iex> MyApp.Person.write_string(people, format: :tsv)
"first_name\tlast_name\tage\nJohn\tDoe\t42\n"