Class: Reading::CSV

Inherits:
Object show all
Defined in:
lib/reading/csv.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(feed = nil, path: nil, config: {}) ⇒ CSV

Returns a new instance of CSV.

Parameters:

  • feed (Object) (defaults to: nil)

    the input source, which must respond to #each_line; if nil, the file at the given path is used.

  • path (String) (defaults to: nil)

    the path of the source file.

  • config (Hash) (defaults to: {})

    a custom config which overrides the defaults, e.g. { errors: { styling: :html } }



28
29
30
31
32
33
34
# File 'lib/reading/csv.rb', line 28

def initialize(feed = nil, path: nil, config: {})
  validate_feed_or_path(feed, path)

  @feed = feed
  @path = path
  @config ||= Config.new(config).hash
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



21
22
23
# File 'lib/reading/csv.rb', line 21

def config
  @config
end

Instance Method Details

#parseArray<Struct>

Parses a CSV reading log into item data (an array of Structs). For what the Structs look like, see the Hash at @default_config[:template] in config.rb. The Structs are identical in structure to that Hash (with every inner Hash replaced with a Struct).

Returns:

  • (Array<Struct>)

    an array of Structs like the template in config.rb



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/reading/csv.rb', line 41

def parse
  feed = @feed || File.open(@path)
  items = []

  feed.each_line do |string|
    line = Line.new(string, self)
    row = line.to_row

    items += row.parse
  end

  items.map(&:to_struct)
ensure
  feed&.close if feed.respond_to?(:close)
end