<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: file code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Thu, 21 Aug 2008 09:28:22 GMT</pubDate>
    <description>DZone Snippets: file code</description>
    <item>
      <title>Prepend a String to a file</title>
      <link>http://snippets.dzone.com/posts/show/4464</link>
      <description>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.&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt;require 'tempfile'&lt;br /&gt;&lt;br /&gt;class File&lt;br /&gt;  def self.prepend(path, string)&lt;br /&gt;    Tempfile.open File.basename(path) do |tempfile|&lt;br /&gt;      # prepend data to tempfile&lt;br /&gt;      tempfile &lt;&lt; string&lt;br /&gt;&lt;br /&gt;      File.open(path, 'r+') do |file|&lt;br /&gt;        # append original data to tempfile&lt;br /&gt;        tempfile &lt;&lt; file.read&lt;br /&gt;        # reset file positions&lt;br /&gt;        file.pos = tempfile.pos = 0&lt;br /&gt;        # copy all data back to original file&lt;br /&gt;        file &lt;&lt; tempfile.read&lt;br /&gt;      end&lt;br /&gt;    end&lt;br /&gt;  end&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Ideas (unverified):&lt;br /&gt;&lt;code&gt;&lt;br /&gt;class FileString &lt; String&lt;br /&gt;  extend Forwardable&lt;br /&gt;&lt;br /&gt;  def initialize(file)&lt;br /&gt;    @file = file.reopen(file.path, 'r+')&lt;br /&gt;    at_exit {@file.close}&lt;br /&gt;  end&lt;br /&gt;&lt;br /&gt;  def_delegators :@file, :&lt;&lt;, :pos, :pos=&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;</description>
      <pubDate>Fri, 24 Aug 2007 19:40:07 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/4464</guid>
      <author>boof (Florian A&#223;mann)</author>
    </item>
  </channel>
</rss>
