Rails: transform Path to Url

Almost 1 hour of digging before i gave up and built this…
Update: thanks for the improvement @ Will Sulzer

  # abs or /abs -> http://myx.com/abs
  # https://grosser.it/2008/11/24/rails-transform-path-to-url
  def path_to_url(path)
    "#{request.protocol}#{request.host_with_port.sub(/:80$/,"")}/#{path.sub(/^\//,"")}"
  end
Advertisements

6 thoughts on “Rails: transform Path to Url

  1. nope, not enough when you got /xy/something (for example an image) and want to generate the url for it
    url_for(‘/path’) only generates ‘/path’ kind of disappointing

  2. Here’s mine. This works in Rails 3.1. I needed to use this method because if was needed a full path to assets, and Rails would only give me the relative paths, i.e. image_path(‘foo’), video_path(‘bar’). It’s too bad that they don’t support image_url, etc..

    def path_to_url(path)
    “#{request.protocol}#{request.host_with_port}#{path}”
    end

  3. That would work for cases where you have a xxx_path, but not when you have some kind of path coming in from somewhere and you need to turn it into an url

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s