Module URI constructor explain

Report
Question

Please briefly explain why you feel this question should be reported .

Report Cancel
require "uri"

u = URI.parse("https://www.google.com")  #<URI::HTTPS https://www.google.com>
v = URI("https://www.google.com")        #<URI::HTTPS https://www.google.com>
u == v                                   # => true

The URI.parse is easy to understand, it calls module_function parse on Module URI.

How to understand URI() in Ruby’s context? What method does it called? Or is this a syntactic sugar?

solved 0
1 Answer 28 views 0

Answer ( 1 )

    3
    November 15, 2016 at 7:42 pm

    Please briefly explain why you feel this answer should be reported .

    Report Cancel

    Best answer on your question is source code. Code below executes when you call URI('http..')

    def URI(uri)
      if uri.is_a?(URI::Generic)
        uri
      elsif uri = String.try_convert(uri)
        URI.parse(uri)
      else
        raise ArgumentError,
          "bad argument (expected URI object or URI string)"
      end
    end
    

    As you can see under the hood this method allows you to pass any argument and be sure that program will throw ArgumentError if argument wasn’t uri or instance of uri. So, in my opinion good practice to use URI('...') than URI.parse('...') with additional checks.

    Feel free to check it out by yourself: github ruby repo mirror

    Best answer

Leave an answer

Browse

What is the capital of Egypt ? ( Cairo )

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>