S
Sam Stephenson
I was reading about mentalguy's lazy.rb and thought it'd be fun to use
lazy evaluation as a vehicle for adding new syntactic sugar to Ruby.=20
Here's one such example, which lets you prefix backticks with a unary
minus to silence stderr:
| % irb -r lazy_backtick
| irb(main):001:0> `hello`
| /opt/local/lib/ruby/1.8/irb/workspace.rb:81: command not found: hello
| =3D> ""
| irb(main):002:0> -`hello`
| =3D> ""
lazy_backtick.rb:
| class LazyBacktick < String
| instance_methods.each {|m| undef_method(m) unless m =3D~ /^__/}
|
| def initialize(command)
| @command, @silence_stderr =3D command, false
| end
|
| def -@
| @swallow_stderr =3D true
| value
| end
|
| def method_missing(method, *arguments, &block)
| value.send(method, *arguments, &block)
| end
|
| private
| def value
| @value ||=3D evaluate
| end
|
| def evaluate
| real_backtick "#@command#{' 2>/dev/null' if @silence_stderr}"
| end
| end
|
| module Kernel
| alias_method :real_backtick, :'`'
|
| def `(command)
| LazyBacktick.new(command)
| end
| end
Note that I'm using the same approach as BlankSlate to remove
LazyBacktick's methods, but inheriting from String instead -- this is
so "String =3D=3D=3D `foo`" doesn't break. (It would be nice to have a mixi=
n
alternative to BlankSlate.)
The way I'm silencing stderr is a bit, um, agile. Can it be made to
work in Ruby on Windows without loading an external library (since
open3 doesn't work there)?
Sam
lazy evaluation as a vehicle for adding new syntactic sugar to Ruby.=20
Here's one such example, which lets you prefix backticks with a unary
minus to silence stderr:
| % irb -r lazy_backtick
| irb(main):001:0> `hello`
| /opt/local/lib/ruby/1.8/irb/workspace.rb:81: command not found: hello
| =3D> ""
| irb(main):002:0> -`hello`
| =3D> ""
lazy_backtick.rb:
| class LazyBacktick < String
| instance_methods.each {|m| undef_method(m) unless m =3D~ /^__/}
|
| def initialize(command)
| @command, @silence_stderr =3D command, false
| end
|
| def -@
| @swallow_stderr =3D true
| value
| end
|
| def method_missing(method, *arguments, &block)
| value.send(method, *arguments, &block)
| end
|
| private
| def value
| @value ||=3D evaluate
| end
|
| def evaluate
| real_backtick "#@command#{' 2>/dev/null' if @silence_stderr}"
| end
| end
|
| module Kernel
| alias_method :real_backtick, :'`'
|
| def `(command)
| LazyBacktick.new(command)
| end
| end
Note that I'm using the same approach as BlankSlate to remove
LazyBacktick's methods, but inheriting from String instead -- this is
so "String =3D=3D=3D `foo`" doesn't break. (It would be nice to have a mixi=
n
alternative to BlankSlate.)
The way I'm silencing stderr is a bit, um, agile. Can it be made to
work in Ruby on Windows without loading an external library (since
open3 doesn't work there)?
Sam