uri snippets

How to fix "bad URI(is not URI?)"

Tagged uri, url, ruby, parse  Languages ruby

This URL contains special characters, which Ruby can't handle:

>> URI.parse 'http://www.yr.no/sted/Finland/Västra_Finland/Askainen/varsel.xml'
URI::InvalidURIError: bad URI(is not URI?): http://www.yr.no/sted/Finland/Västra_Finland/Askainen/varsel.xml
    from /usr/local/lib/ruby/1.8/uri/common.rb:436:in split'
    from /usr/local/lib/ruby/1.8/uri/common.rb:485:in parse'
    from (irb):5

Your browser can probably open the URL. To fix this error encode the URL before handing it to the parse method:

=> #<URI::HTTP:0x18bfb40 URL:http://www.yr.no/sted/Finland/V%C3%A4stra_Finland/Askainen/varsel.xml>

How to generate URLs in your Rails model

Tagged to_uri, uri, routes, model  Languages ruby

You can use helpers in your model by first including them:

class Post < ActiveRecord::Base
  include ActionController::UrlWriter
  def to_uri

Some might consider this heresy, I don't. In my opinion it's similar to the to_param method. You could of course move it to a delegate class or something similar.