Ruby using namespace/module Ruby using namespace/module ruby ruby

Ruby using namespace/module


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::HTTPGet = 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.


I hope this example will clarify things.

module Foo  def foo    "foo"  endendclass Bar  include Foo  def bar    "bar"  endendBar.new.foo # fooBar.new.bar # barclass Baz  extend Foo  self.def baz    "baz"  endendBaz.foo # fooBaz.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.


require 'net/http'uri = URI('http://example.com/some_path?query=string')httpns = Net::HTTPdef get(uri)   httpns::Get.new uriendhttp.start(uri.host, uri.port) do |http|  request = get uri  response = http.request request # Net::HTTPResponse objectend

in your class.