Module: Readlines::Convert

Included in:
ReadDuc
Defined in:
lib/readlines/readlines/convert.rb

Instance Method Summary collapse

Instance Method Details

#convert_encoding_now(from_encoding, to_encoding) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


8
9
10
11
12
13
# File 'lib/readlines/readlines/convert.rb', line 8

def convert_encoding_now(from_encoding, to_encoding)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.read(@file_path, encoding: from_encoding)
  ::File.write(@file_path, content.encode(to_encoding))
end

#convert_to_array_nowObject

Raises:

  • (Readlines::NotFoundError)


36
37
38
39
40
41
# File 'lib/readlines/readlines/convert.rb', line 36

def convert_to_array_now
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.readlines(@file_path)
  content.map(&:chomp)
end

#convert_to_format_now(format) ⇒ Object

Raises:

  • (Readlines::NotFoundError)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/readlines/readlines/convert.rb', line 15

def convert_to_format_now(format)
  raise Readlines::NotFoundError, "File not found: #{@file_path}" unless ::File.exist?(@file_path)

  content = ::File.read(@file_path)

  case format.downcase
  when 'txt'
  when 'csv'
    content = content.lines.map { |line| line.strip.split(',') }.map { |fields| fields.join(',') }.join("\n")
  when 'json'
    data = content.lines.map { |line| line.strip.split(',') }
    content = JSON.pretty_generate(data)
  else
    raise ArgumentError, "Unsupported format: #{format}. Supported formats are .txt, .csv, and .json."
  end

  converted_file_path = "#{::File.basename(@file_path, ::File.extname(@file_path))}-copy.#{format.downcase.delete('.')}"
  ::File.write(converted_file_path, content)
  converted_file_path
end