On 11/2/07, Alex Gutteridge <alexg / kuicr.kyoto-u.ac.jp> wrote:
>
> Ara, out of curiosity, is there any reason why you don't write the
> Kernel modification code as:
>
> module Kernel
>    H = {}
>    def requiree(of)
>      H[of]
>    end
>
>    alias :old_require :require
>    def require(*a)
>      old_require(*a)
>      H[a.first] = caller
>    end
> end
>
> Is there any difference between the two versions, or is it just a
> style preference?
>
> Alex Gutteridge
>
> Bioinformatics Center
> Kyoto University

It's a preference for code that will work even if someone else wants
to intercept require.

Try this:

module Kernel
  H = {}
  def requiree(of)
    H[of]
  end

  alias :old_require :require
  def require(*a)
    old_require(*a)
    H[a.first] = caller
  end
end

# in another file someone has the same idea...
module Kernel
  alias :old_require :require
  def require(*a)
    old_require(*a)
    puts "I want to intercept require too"
  end
end

require 'date'

puts "Here"
__END__
$ ruby alias-require.rb
alias-require.rb:9:in `old_require': stack level too deep (SystemStackError)
        from alias-require.rb:9:in `old_require'
        from alias-require.rb:18:in `require'
        from alias-require.rb:23

Using alias is just a little too fragile. You could always generate a
unique alias name (using GUID or something) which would avoid the
problem, but grabbing a reference to the existing method and using
that is sure to work.

Regards,
Sean