Zach Dennis
3/29/2006 8:13:00 AM
Mirek wrote:
>>i think you can do
>>::open
>
>
> require 'open-uri'
>
> class C
> def open(uri)
> ::open(uri)
> end
> end
>
> o = C.new
> o.open('x')
>
> ---
>
> open.rb:6: syntax error, unexpected tIDENTIFIER, expecting tCONSTANT
> ::open(uri)
> ^
>
:: is use to find a toplevel constant, It is not used for method lookups. ie:
A = true
class B; end
module C; end
If you are deeply nested you can work your way out by using ::
A = true
class B
class A # inner class
end
def open
puts "A is #{A}" #puts A::B
end
def open2
puts "A is #{::A}" #puts true, because our toplevel constant A is true
end
end
It is more useful when you are inside of a class or module namespace, and you have an inner class
with a clashing or similar name. E.g: Socket or String, and instead of using that one, you want to
use the toplevel namespace to find what you are looking for.
The code "require 'open-uri'" actually adds the *private* method 'open' to to the Kernel module. The
Kernel module is included (or as folks call it, mixed in) in Object. Every class inherits from
Object, so every class gets the *new* private open method.
So for your example you could invoke super in your open call to make sure it gets passed up the
chain to Kernel#open.:
require 'open-uri'
class C
def open(uri)
super
end
end
o = C.new
o.open('x')
Hope this helps,
Zach