4

So I wish to override backticks in a testing file, and have this apply to all scripts that are called during testing. The testing file employs several classes (saved in other files), and when these classes use backticks the override I have in the testing file does not apply.

e.g. The following is in the testing file (tc_some_test.rb)

module BacktickURI
  def `(uri)
    # `untrick beautifier
    puts "uri = #{uri}\n"
    if uri =~ /some command/
      puts "command ran #{uri}\n"
    else
      system("#{uri} 2>&1")
    end
  end
end

include BacktickURI

For all backticks used in tc_some_test.rb, this works but external classes and scripts that are called still use the normal, non-overridden backticks.

Any help is appreciated. An alternative could be a way to override methods in one script/file from a different script/file.

Robin
  • 737
  • 2
  • 10
  • 23
  • Backticks are used to execute system commands, no way you're gonna override them that easily! – Anthony Alberto Jan 18 '13 at 01:31
  • 1
    Please note this *works* in Ruby: `def \`(x); puts s; end; \`hi\`` => `hi` So, uhm, they *can* be overridden in MRI 1.8 .. now, the question is, "How to get method X in scope Y?" –  Jan 18 '13 at 01:36
  • @theTinMan: Well, yes, this code proves that you can override backticks a little more than you can override `"` or `'` :) – Ry- Jan 18 '13 at 01:37
  • 2
    I did some searching and dug around in [Kernel](http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-60), and, yes, it is possible to override them, so I stand corrected. Do I think it's a good practice? Definitely not, because it's changing the expected behavior of a core method in a core library; It also messes with `%x`, changing its behavior, so, tread very carefully. – the Tin Man Jan 18 '13 at 01:44
  • 1
    I am aware it's bad practice. But as a temporary quick fix I figure it's ok. So how does one do what I asked then? – Robin Jan 18 '13 at 01:49

2 Answers2

2

Type in irb:

define_singleton_method '`' do |*| puts 'kokot' end

`ls`
#=> kokot
Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74
1

Try this:

module BacktickURI
  def included(klass)
    klass.class_eval do
      define_method("`") do |uri|
        puts "uri = #{uri}\n"
        if uri =~ /some command/
          puts "command ran #{uri}\n"
        else
          system("#{uri} 2>&1")
        end
      end
    end
  end
end
Linuxios
  • 34,849
  • 13
  • 91
  • 116