Method: Nanoc::DataSources::Filesystem::Tools.read_file

Defined in:
lib/nanoc/data_sources/filesystem/tools.rb

.read_file(filename, config:) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Reads the content of the file with the given name and returns a string in UTF-8 encoding. The original encoding of the string is derived from the default external encoding, but this can be overridden by the “encoding” configuration attribute in the data source configuration.



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/nanoc/data_sources/filesystem/tools.rb', line 164

def read_file(filename, config:)
  # Read
  begin
    data = File.read(filename)
  rescue => e
    raise Errors::FileUnreadable.new(filename, e)
  end

  # Set original encoding, if any
  if config && config[:encoding]
    original_encoding = Encoding.find(config[:encoding])
    data.force_encoding(config[:encoding])
  else
    original_encoding = data.encoding
  end

  # Set encoding to UTF-8
  begin
    data.encode!('UTF-8')
  rescue
    raise Errors::InvalidEncoding.new(filename, original_encoding)
  end

  # Verify
  unless data.valid_encoding?
    raise Errors::InvalidEncoding.new(filename, original_encoding)
  end

  # Remove UTF-8 BOM (ugly)
  data.delete!("\xEF\xBB\xBF")

  data
end