Skip to content

Instantly share code, notes, and snippets.

@piotr-galas
Created June 4, 2020 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotr-galas/d46cf784ee90f8124d1e9c11dabb4775 to your computer and use it in GitHub Desktop.
Save piotr-galas/d46cf784ee90f8124d1e9c11dabb4775 to your computer and use it in GitHub Desktop.
require "pry"
require "csv"
class GenerateCsvSummary
NUMBER_OF_ROWS = 10
GENERATED_FILE_PATH = "./csv_summary.csv"
def initialize(absolute_directory_path)
@absolute_directory_path = absolute_directory_path
end
def call
create_empty_output_file
Dir.foreach(@absolute_directory_path) do |filename|
next unless File.extname(filename) == ".csv"
EncodeFile.new("#{@absolute_directory_path}/#{filename}").call
AddFileRows.new("#{@absolute_directory_path}/#{filename}", GENERATED_FILE_PATH, NUMBER_OF_ROWS).call
end
end
def create_empty_output_file
FileUtils.touch(GENERATED_FILE_PATH)
File.open(GENERATED_FILE_PATH, "w") { |file| file.truncate(0) }
end
end
class EncodeFile
def initialize(csv_file_path)
@csv_file_path = csv_file_path
@output = "#{@csv_file_path}x"
end
def call
text = File.read(@csv_file_path)
text_without_invalid = text.encode("UTF-8", invalid: :replace, replace: " ")
File.write(@csv_file_path, text_without_invalid)
end
end
class AddFileRows
def initialize(csv_file_path, generated_file_path, number_of_rows)
@csv_file_path = csv_file_path
@generated_file_path = generated_file_path
@number_of_rows = number_of_rows
end
def call
CSV.open(@generated_file_path, "a+") do |csv|
csv << []
csv << []
csv << [File.basename(@csv_file_path, ".csv")]
csv << rows.first.headers
rows.each do |row|
csv << row
end
end
end
def rows
rows = CSV.open(@csv_file_path, "r", col_sep: ",", headers: true) { |csv| csv.first(@number_of_rows) }
end
end
GenerateCsvSummary.new("/Users/piotr/Downloads/jazzhr").call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment