Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Prepend A String To A File

DZone's Guide to

Prepend A String To A File

·
Free Resource
I happen to read a question on the ruby ML that inspired me to monkey patch (not really since this method does not exist...) the file class. I added a method called prepend to the File class. You need to require 'tempfile' or this patch will raise a NameError, imho.


require 'tempfile'

class File
  def self.prepend(path, string)
    Tempfile.open File.basename(path) do |tempfile|
      # prepend data to tempfile
      tempfile << string

      File.open(path, 'r+') do |file|
        # append original data to tempfile
        tempfile << file.read
        # reset file positions
        file.pos = tempfile.pos = 0
        # copy all data back to original file
        file << tempfile.read
      end
    end
  end
end


Ideas (unverified):

class FileString < String
  extend Forwardable

  def initialize(file)
    @file = file.reopen(file.path, 'r+')
    at_exit {@file.close}
  end

  def_delegators :@file, :<<, :pos, :pos=
end


Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}