Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby using namespace/module

For example:

require 'net/http'
uri = URI('http://example.com/some_path?query=string')

Net::HTTP.start(uri.host, uri.port) do |http|
  request = Net::HTTP::Get.new uri

  response = http.request request # Net::HTTPResponse object
end

What is the correct/rubist way to get rid of Net::HTTP ? i.e. HTTP::Get.new() or just Get.new()

like image 618
w00d Avatar asked Jun 25 '13 14:06

w00d


People also ask

How do you use namespaces in Ruby?

The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter. You can access the sub members of double with the help of :: operator.

How do you call a module method in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

Can you instantiate a module in Ruby?

You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module.

How do I import a module into Ruby?

include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.


1 Answers

If you want to shorten these, you can just import that namespace:

Net::HTTP.start(...)

include Net
# HTTP.start(...)

Be careful when you import aggressively as it might cause conflict within your class if you get carried away.

An alternative is to create aliases:

HTTP = Net::HTTP
Get = Net::HTTP::Get

The "correct" way is to just spell it out and not get too flustered by that. A typical Ruby program will bury this sort of low-level behavior beneath an abstraction layer so it's rarely a big deal.

like image 87
tadman Avatar answered Sep 28 '22 08:09

tadman