berkes
berkes

Reputation: 27553

URI() is not the usual Ruby receiver.message format, what is it?

The Ruby core URI module is called in a strange way:

URI("http://example.com")

It is not the usual receiver.message format, so what does Ruby call and do here? Is it a shortcut for URI.new() or is it Kernel.URI(), or something completely different?

Upvotes: 1

Views: 38

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369438

It is the normal message sending format. If you don't specify an explicit receiver, Ruby will assume an implicit receiver of self.

However, in this particular case, the receiver is actually irrelevant, because the method doesn't do anything interesting (call private methods or access instance variables) with self. Such methods, which are called with an implicit receiver of self but don't actually do anything with self are usually defined as private instance methods of Kernel, which, being mixed into Object is in the ancestry chain of almost every Ruby object.

So, in this particular case, the method is Kernel#URI. Other similar methods include Kernel#Integer, Kernel#Float, Kernel#Array, Kernel#String, Kernel#require, Kernel#puts, Kernel#load, Kernel#p, Kernel#gets, etc.


Unless they are only meant to be called within a module body, in which case they are defined in Module, e.g. Module#attr_reader, Module#attr_writer, Module#attr_accessor, Module#define_method, etc.

Upvotes: 1

Mosselman
Mosselman

Reputation: 1748

Yes it is Kernel::URI

http://rxr.whitequark.org/mri/source/lib/uri/common.rb#1228

I suspect you were trying to stub it. I was trying to do so myself, but I have not managed to stub it out with rspec. I ended up using the WebMock gem.

Upvotes: 1

Related Questions