Simple File Manipulation
Posted by root Mon, 21 Jul 2008 22:15:00 GMT
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
endThen 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.