-
Notifications
You must be signed in to change notification settings - Fork 109
/
csv_encoder.ex
46 lines (38 loc) · 1.39 KB
/
csv_encoder.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
defmodule Crawly.Pipelines.CSVEncoder do
@moduledoc """
Encodes a given item (map) into CSV. Does not flatten nested maps.
### Options
If no fields are given, the item is dropped from the pipeline.
- `:fields`, required: The fields to extract out from the scraped item. Falls back to the global config `:item`.
### Example Usage
iex> item = %{my: "first", other: "second", ignore: "this_field"}
iex> Crawly.Pipelines.CSVEncoder.run(item, %{}, fields: [:my, :other])
{"first,second", %{}}
"""
@behaviour Crawly.Pipeline
require Logger
@impl Crawly.Pipeline
@spec run(map, map, fields: list(atom)) ::
{false, state :: map} | {csv_line :: String.t(), state :: map}
def run(item, state, opts \\ []) do
opts = Enum.into(opts, %{fields: nil})
fields = Map.get(opts, :fields) || Application.get_env(:crawly, :item)
case fields do
:undefined ->
# only for when both tuple and global config is not provided
Logger.info(
"Dropping item: #{inspect(item)}. Reason: No fields declared for CSVEncoder"
)
{false, state}
fields ->
new_item =
Enum.reduce(fields, "", fn
field, "" ->
"#{inspect(Map.get(item, field, ""))}"
field, acc ->
acc <> "," <> "#{inspect(Map.get(item, field, ""))}"
end)
{new_item, state}
end
end
end