Module: Eco::Data::Files::InstanceMethods

Includes:
Encoding, Language::AuxiliarLogger
Included in:
Eco::Data::Files
Defined in:
lib/eco/data/files/helpers.rb

Constant Summary

Constants included from Encoding

Encoding::BOM_BYTES

Instance Attribute Summary

Attributes included from Language::AuxiliarLogger

#logger

Instance Method Summary collapse

Methods included from Encoding

#encoding, #file_empty?, #file_exists?, #get_file_content_with_encoding, #has_bom?, #remove_bom, #scoped_encoding

Methods included from Language::AuxiliarLogger

#log

Instance Method Details

#get_file_content(file, encoding: nil, tolerance: 5) ⇒ String

It offers a resilient way to read content from a file

Returns:

  • (String)

    the content of the file



21
22
23
# File 'lib/eco/data/files/helpers.rb', line 21

def get_file_content(file, encoding: nil, tolerance: 5)
  read_with_tolerance(file, encoding: encoding, tolerance: tolerance)
end

#read_with_tolerance(file, encoding:, tolerance: 5) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/eco/data/files/helpers.rb', line 25

def read_with_tolerance(file, encoding:, tolerance: 5)
  content = get_file_content_with_encoding(file, encoding: encoding)
  return nil unless content

  content.scrub do |bytes|
    replacement = "<#{bytes.unpack1('H*')}>"

    if tolerance <= 0
      logger.error("There were more than 5 encoding errors in the file '#{file}'.")
      return content
    else
      tolerance -= 1
      logger.error("Encoding problem in file '#{file}': '#{replacement}'.")
      replacement
    end
  end
end