How to get an absolute url for an asset in Rails 3.1?

image_path returns only the path (without a host).

The url_for helper url_for not accept any paths, so something like url_for(image_path('image.png')) will not work. Although the inner url_for in ActionDispatch::Http::Url.url_for seems to do the trick ( source ), there seems to be no open interface for it.

How should I do it? Ultimately, it would be nice to have a function like image_url that works like url_for for routes, so I could call image_url('image.png') and get the absolute URL given to all default_url_options .

+45
ruby-on-rails ruby-on-rails-3
Jun 27 '11 at 23:15
source share
6 answers

It seems that recently, sass-rails now interprets the image_url command in the image_url file in the expected way, allowing the final location of the corresponding image.

+4
Aug 08 2018-11-11T00:
source share
 def image_url(source) URI.join(root_url, image_path(source)) end 

This way you get the URL either using assets_host or using root_url.

+49
01 Sep '12 at 23:26
source share

Try this in application_helper.rb (from one of the comments on the Spike page):

 def image_url(source) "#{root_url}#{image_path(source)}" end 
+14
Aug 08 2018-11-11T00:
source share

Our manufacturing and intermediate assets are located on s3 / cloudfront ... but not locally / dev. So I wrote this (maybe unnecessarily, and probably can be simplified):

  def get_digest_file(source) return asset_path(source.to_s.downcase) unless Rails.application.config.assets.digests.present? return ActionController::Base.asset_host + "/assets/" + Rails.application.config.assets.digests[source.to_s.downcase] end 
+7
Sep 18 '12 at 18:55
source share

From Full URL to Image Path in Rails 3

 request.protocol + request.host_with_port + image_path('image.png') 

You can even create a DRY helper, something like

 def full_image_path(img_path) request.protocol + request.host_with_port + image_path(img_path) end 
+4
Apr 29 '12 at 2:00
source share

You can define css with an absolute URL for any background image or other assets. That way you can generate it dynamically after that. How to get absolute image paths in your css files using sass / scss .

CSS

 body { background-image: image-url(background.png); } 

In your environment file change it with

 config.action_controller.asset_host = "http://your.domain.com/" 

Then your css will look something like this:

 body { background-image: url(http://your.domain.com/assets/background.png); } 
0
Jan 14 '14 at 10:44
source share



All Articles