Class: Csvtool::Application::UseCases::RunRowRandomization

Inherits:
Object
  • Object
show all
Defined in:
lib/csvtool/application/use_cases/run_row_randomization.rb

Defined Under Namespace

Classes: Result

Instance Method Summary collapse

Constructor Details

#initialize(header_reader: Infrastructure::CSV::HeaderReader.new, row_randomizer: Infrastructure::CSV::RowRandomizer.new, csv_randomized_row_file_writer: nil) ⇒ RunRowRandomization

Returns a new instance of RunRowRandomization.



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/csvtool/application/use_cases/run_row_randomization.rb', line 18

def initialize(
  header_reader: Infrastructure::CSV::HeaderReader.new,
  row_randomizer: Infrastructure::CSV::RowRandomizer.new,
  csv_randomized_row_file_writer: nil
)
  @header_reader = header_reader
  @row_randomizer = row_randomizer
  @csv_randomized_row_file_writer = csv_randomized_row_file_writer || Infrastructure::Output::CsvRandomizedRowFileWriter.new(
    row_randomizer: @row_randomizer
  )
end

Instance Method Details

#randomize(session:, headers:, on_row: nil) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/csvtool/application/use_cases/run_row_randomization.rb', line 46

def randomize(session:, headers:, on_row: nil)
  if session.output_destination.file?
    @csv_randomized_row_file_writer.call(
      path: session.output_destination.path,
      headers: headers,
      file_path: session.source.path,
      col_sep: session.source.separator,
      headers_present: session.source.headers_present?,
      seed: session.options.seed
    )
    success(output_path: session.output_destination.path)
  else
    @row_randomizer.each(
      file_path: session.source.path,
      col_sep: session.source.separator,
      headers: session.source.headers_present?,
      seed: session.options.seed
    ) { |fields| on_row.call(fields) if on_row }
    success({})
  end
rescue CSV::MalformedCSVError
  failure(:could_not_parse_csv)
rescue Errno::EACCES, Errno::ENOENT => e
  if session.output_destination.file?
    failure(:cannot_write_output_file, path: session.output_destination.path, error_class: e.class)
  else
    failure(:cannot_read_file, path: session.source.path)
  end
end

#read_headers(file_path:, col_sep:, headers_present:) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/csvtool/application/use_cases/run_row_randomization.rb', line 30

def read_headers(file_path:, col_sep:, headers_present:)
  return failure(:file_not_found, path: file_path) unless File.file?(file_path)

  headers = nil
  if headers_present
    headers = @header_reader.call(file_path: file_path, col_sep: col_sep)
    return failure(:no_headers) if headers.empty?
  end

  success(headers: headers)
rescue CSV::MalformedCSVError
  failure(:could_not_parse_csv)
rescue Errno::EACCES
  failure(:cannot_read_file, path: file_path)
end