Prepend a String to a file
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