views:

17

answers:

3

How do I return an image inside the respond_to do |format| block?

I already have the image fully assembled (i.e. no ugly assembling from blogs) and at a particular URL (because it's in the public folder), I just need to be able to return that image for a particular other URL query.

For example, the image is in

public/cars/userid/car_id/random_name.JPG

and I want to be able to serve up that image when a user goes to

http://mywebsite.com/car_id.JPG

because it's prohibitive to have the user have to know the userid and random_name. I have the url public/cars/userid/car_id/random_name.JPG already as @car.public_filename, because @car is a attachment_fu object.

+1  A: 

You can redirect the browser to the image:

redirect_to @car.public_filename
Matt
Sorry, I guess I should have been more clear. I want to hide the details of the storage from the user. [*Edit*: Redacting comment about redirection for embedding images in pages; seems like it should be okay from that standpoint.]
unsorted
Also, when I tell rails to respond to format.jpg it gives me an error about a nonexistent MimeType JPG. Any ideas on how to make it handle it anyway? Thanks for your fast response.
unsorted
mime types for images are formatted like: `'image/jpg'`, `'image/jpeg'`, `'image/png'`, `'image/gif'` etc. If image mime types aren't added in by default, see Matt's other answer for how to register additional types.
Jeremy
A: 

If you want to use another mime-type in respond_to, you can add it in config/initializers/mime_types.rb. Here's an example:

Mime::Type.register "text/richtext", :rtf
Matt
+1  A: 

You can also write a small Metal middleware to reroute all the /car_id.JPG url to the real file:

#app/metal/serve_car.rb
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class ServeCar
  def self.call(env)
    if env["PATH_INFO"] =~ /^\/car_(\d+).JPG$/
      path = Car.find($1).public_filename
      [302, {"Content-Type" => "text/html", "Location" => path}, ["You are being redirected"]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end
hellvinz