Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing images on production, from javascript, in Rails 4

It appears that now in Rails 4 using asset pipeline and the sprocket-rails gem, when images are processed, their filename is appended with an md5 fingerprint like css and javascript. While this makes sense because md5 fingerprints are awesome, it makes it increasingly difficult to access that image from javascript. In rails 3.2, I could access the image with /assets/image_name.jpg and it would serve properly, but in rails 4 that asset doesn't exist, it only exists with the md5 fingerprint in the name.

I know that rails provides helpers to access the image via erb <%= asset-url("image_name.jpg") %> but that is less ideal in javascript, because I am not using erb in my js. There are plenty of ways I could hack this with data-attributes serving in the views or using a script tag in my view and setting some globals, but I am looking for a nice solution to this problem, if it exists.

Any help is appreciated, thanks.

like image 502
Bryan Ashley Avatar asked Feb 14 '14 16:02

Bryan Ashley


1 Answers

Another option to consider (although I wouldn't recommend it) is to use a custom route in your application controller to grab the asset path for you in the controller and either return the url to the asset with the md5 hash or possibly just render the raw binary data of the asset (although this will add processing overhead to your application).

For example, you make a AJAX get request to http://yourapp.com/images?file=my_image.jpg

Then in your controller your action method would look like this:

def images
  ActionController::Base.helpers.asset_url(params[:file])
end

This would then return the url path to the asset. The downside to this method is that it requires that you make two requests on the JS side. The first to get the path to the asset and the second to actually load that asset with the returned path.

To reduce this down to one request you could have the application read the image from the file system and return the proper headers so the browser thinks it is an image being returned and therefor will render the url provided. However, this would be a lot more work for the application and a lot more unneeded disk IO on your server.

It may take two requests for each image on the client to achieve what you want but you have to sacrifice somewhere...

like image 142
John Saltarelli Avatar answered Oct 08 '22 20:10

John Saltarelli