Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there something like a null-stream in Ruby?

Tags:

stream

ruby

I could use:

File.open('/dev/null', 'w') 

on Unix systems, but if there is a Ruby way to achieve this, I'd like to use it. I am just looking for an I/O stream, that immediately "trashes" all writes, kind of like a null-object.

like image 802
Marian Theisen Avatar asked Dec 30 '11 16:12

Marian Theisen


2 Answers

If you want the full behavior of streams, the best is probably to use:

File.open(File::NULL, "w") 

Note that File::NULL is new to Ruby 1.9.3; you can use my backports gem:

require 'backports/1.9.3/file/null' # => Won't do anything in 1.9.3+ File.open(File::NULL, "w")          # => works even in Ruby 1.8.6 

You could also copy the relevant code if you prefer.

like image 96
Marc-André Lafortune Avatar answered Oct 03 '22 09:10

Marc-André Lafortune


There's stringIO, which I find useful when I want to introduce a dummy filestream:

require "stringio" f = StringIO.new f.gets # => nil 

And here's some code from heckle that finds the bit bucket for both Unix and Windows, slightly modified:

# Is this platform MS Windows-like? # Actually, I suspect the following line is not very reliable. WINDOWS = RUBY_PLATFORM =~ /mswin/ # Path to the bit bucket. NULL_PATH = WINDOWS ? 'NUL:' : '/dev/null' 
like image 33
Andrew Grimm Avatar answered Oct 03 '22 11:10

Andrew Grimm