Emmanuel Oga’s Weblog

Handling URIs in ruby a walk in the park? Don’t think so….

Posteado por: emmanueloga en: Octubre 17, 2008

I got sick an tired of juggling around with String urls and URI objects just to get a correct URI for http GETting, POSTing, etc…

For example, if you

Net::HTTP.post_form URI(“www.somewhere.com”)

you get an error…. but if you

Net::HTTP.post_form URI(“www.somewhere.com/”)

(notice trailing slash) you don’t… Boring stuff. The URI lib does provide a normalize method, but it does not always add the trailing “/”. For consistency I wanted normalize to add the trailing slash always. Update: seems like my “consistency” politic is not correct…. Oh, well… at least google does not like it. :-) I’m updating my Gist to remove that behavior…. Off course! Adding a trailing slash means you are looking for a directory and not for a resource, so you can’t go berserk adding trailing slashes in all your urls :p

But, the most boring stuff is joining uris and adding query params to them… This should be simple, right?:

uri = URI("something.com/?some=params")
uri.query = "other=params" # WRONG, previous params are overwritten
uri = URI("something.com/")
uri.query << "other=params" # WRONG, previous query is nil
uri = URI("something.com/?some=params")
uri.query << "other=params" # WRONG, params should be joined with & char...

We need to juggle with the URI object to get the job done. More boring stuff. I wrote two simple methods to handle these problems. Now I won’t have to manually tweak those urls again… never more! (I hope :-) .

  describe NormalizeURI do
    it "should add scheme and final / to an uri" do
      NormalizeURI("www.yahoo.com?something=true").to_s.should == "http://www.yahoo.com/?something=true"
    end
  end

  describe JoinURI do
    it "should join a string, an uri and additional query params" do
      one = URI("www.yahoo.com?uno=dos")
      two = URI("/peteco/carabal?tres=4&cinco=seis")
      result = "http://www.yahoo.com/peteco/carabal/?uno=dos&tres=4&cinco=seis"
      JoinURI(one.to_s, two, :more => :params).should.to_s == "#{ result }&more=params"
    end
  end

This is such small stuff I don’t think a gem for this would be cool…. maybe later (no gemspec fighting yet hehe). And yes, because I’m lazy I’m using active_support this time…. I’m using this inside rails anyways.

Etiquetas: , ,

2 comentarios para "Handling URIs in ruby a walk in the park? Don’t think so…."

Nice. But I needed to add require “uri” at the top for it to run standalone for the tests…

I’ve began materializing this on a gem http://github.com/EmmanuelOga/hurry/ but haven’t had much time to give it a cleanup yet. It’s kinda usable though

Escribe un comentario