3

Does Rails have a built in helper to get the url of an image in the asset pipeline?

path_to_image('image.jpg')

gets the relative path.

url_to_image('image.jpg')

doesn't seem to work.

"#{root_url}#{path_to_image('image.jpg')}"

is not very convenient (and gives an extra / between the root and the image path).

Is there a built in method that I'm overlooking? Or do I need to create a helper?

Andy Harvey
  • 12,333
  • 17
  • 93
  • 185

2 Answers2

4

It doesn't look like this is built into Rails.

In the end I resorted to a helper method

def image_url(file)
  request.protocol + request.host_with_port + path_to_image(file)
end

This approach gets around the double slash issue of using root_url + image_path(file)

Andy Harvey
  • 12,333
  • 17
  • 93
  • 185
1

You are looking for image_path

Duplicate : Getting the image URL without the HTML in Rails

More info : http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_path

Update

A helper that could derive your task.

def image_url(source)
  "#{root_url}#{image_path(source)}"
end
Community
  • 1
  • 1
Trip
  • 26,756
  • 46
  • 158
  • 277
  • thanks Trip. image_path is an alias to path_to_image. Unfortuanetly it doesnt work in this case – Andy Harvey Jun 17 '12 at 16:02
  • Hey Andy, is it that it doesn't work? Or is it that that is not what you are looking for? – Trip Jun 17 '12 at 16:57
  • 'image_path' is the same as 'path_to_image'. It is what I'm already using – Andy Harvey Jun 17 '12 at 17:02
  • Not sure what it is you're looking for. – Trip Jun 17 '12 at 17:06
  • i;m looking for a helper that interacts with the asset pipeline, and returns something like `http://example.com/assets/image.jpg`. Both the `image_path` and the `path_to_image` helpers return `/assets/image.jpg`. Appreciate any suggestions you may have. – Andy Harvey Jun 17 '12 at 17:32
  • Hmm.. I would imagine you would have to build something custom then in a helper for this. The reason being that image_path and its alias only go to the root and not the `host` is because the `host` in any given application could be three or more different parts. But its' helper wouldn't be too difficult. Updated above. – Trip Jun 18 '12 at 08:51