Method: File.nl_convert

Defined in:
lib/ptools.rb

.nl_convert(old_file, new_file = old_file, platform = 'local') ⇒ Object

Converts a text file from one OS platform format to another, ala 'dos2unix'. The possible values for platform include:

  • MS Windows -> dos, windows, win32, mswin
  • Unix/BSD -> unix, linux, bsd, osx, darwin, sunos, solaris
  • Mac -> mac, macintosh, apple

You may also specify 'local', in which case your CONFIG value will be used. This is the default.

Note that this method is only valid for an ftype of "file". Otherwise a TypeError will be raised. If an invalid format value is received, an ArgumentError is raised.

Raises:

  • (ArgumentError)


285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/ptools.rb', line 285

def self.nl_convert(old_file, new_file = old_file, platform = 'local')
  raise ArgumentError, 'Only valid for plain text files' unless File::Stat.new(old_file).file?

  format = nl_for_platform(platform)

  if old_file == new_file
    require 'tempfile'
    temp_name = Time.new.strftime('%Y%m%d%H%M%S')
    Tempfile.open("ruby_temp_#{temp_name}") do |nf|
      File.foreach(old_file) do |line|
        line.chomp!
        nf.print("#{line}#{format}")
      end
      nf.close
      require 'fileutils'
      File.delete(old_file)
      FileUtils.mv(nf.path, old_file)
    end
  else
    File.open(new_file, 'w') do |nf|
      File.foreach(old_file) do |line|
        line.chomp!
        nf.print("#{line}#{format}")
      end
    end
  end

  self
end