Simple File Manipulation

Jul 21
2008

Ruby file manipulation is as easy as:

MyFile.create "test.txt"
MyFile.add "test.txt", "some content"
MyFile.remove "test.txt"

For example create a file caled fileeasy.rb and add the following module to it:

module FileEasy
 
  def self.included(subject)
    subject.extend(ClassMethods)
  end
 
  module ClassMethods
   alias_method :delete, :remove
   alias_method :unlink, :remove
 
    def create(filename)
      File.open(filename, "w")
    end
    def add(filename, text)
      File.open(filename, "a"){ |f| f < < text }
    end
    def remove(filename)
      File.delete(filename)
    end
  end
 
end

Then test it with irb:

require 'fileeasy'
 
class MyClass
  include FileEasy
end
 
MyFile.create "text.txt"
MyFile.add "text.txt", "test content"
MyFile.remove "text.txt"

Of course this post is just a simple tutorial and the standard library is the best choice – FileUtils.

Comments are closed.

Calendar

July 2008
M T W T F S S
« Jun   Aug »
 123456
78910111213
14151617181920
21222324252627
28293031  

Tags