Wednesday, February 13, 2008

Using :db_file with attachment_fu

The README for attachment_fu says that accessing data using the :db_file backend is outside the scope of the document. Well here is my take on it. You will also need the "mimetype_fu" plugin. Follow the instructions with attachment_fu as usual, and do the following.

Assuming that your attachment model is called "Asset" add the following line to "config/routes.rb":
map.asset_data '/asset/:id', :controller => 'assets', :action => 'show'

Create an AssetController containing at least the following:
(The thumbnail of the original image is found if necessary, and mimetype_fu is used to determine the mime-type sent to the browser)
class AssetsController < ApplicationController
def show
asset = Asset.find(params[:id])
if params[:thumbnail]
data = asset.thumbnails.find_by_thumbnail(params[:thumbnail])
end
data ||= asset
send_data (data.db_file.data,
:filename => data.filename,
:type => File.mime_type?(data.filename),
:disposition => 'inline')
end
end

Add this method to app/helpers/application_helper.rb
  def assetpath(asset,thumb=nil)
"#{asset_data_url(:id => asset.id)}#{thumb.nil? ? '' : "?thumbnail=#{thumb.to_s}"}"
end


So now you may use the helper in your views (i.e.):
<%= image_tag(assetpath(asset_model_instance)) %>
<%= image_tag(assetpath(asset_model_instance,:thumb)) %>

No comments: