15

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()

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
w00d
  • 5,416
  • 12
  • 53
  • 85

3 Answers3

19

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.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • I can't `include Net::HTTP`, it throws error: `TypeError: wrong argument type Class (expected Module)` – w00d Jun 25 '13 at 14:44
  • 2
    Ah, I should remove that then. `include` only works on modules, but it's hard to tell how these things are structured by just looking at use cases. Aliases might work better. In any case, typing `Net::HTTP` is something that makes it abundantly clear what you're doing, and hiding that is usually a bad idea. – tadman Jun 25 '13 at 17:51
6

I hope this example will clarify things.

module Foo
  def foo
    "foo"
  end
end

class Bar
  include Foo

  def bar
    "bar"
  end
end

Bar.new.foo # foo
Bar.new.bar # bar

class Baz
  extend Foo

  self.def baz
    "baz"
  end
end

Baz.foo # foo
Baz.baz # baz

Make sure you know what you are doing when you use import or extend. You could end up overriding a method that you might not want to override.

mess110
  • 81
  • 3
2
require 'net/http'
uri = URI('http://example.com/some_path?query=string')

httpns = Net::HTTP

def get(uri)
   httpns::Get.new uri
end

http.start(uri.host, uri.port) do |http|
  request = get uri

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

in your class.

Paul
  • 25,812
  • 38
  • 124
  • 247