Paperclip

結局昨日悩んでいたのは「画像と他の情報とを1つのテーブルに
混在させているのが原因」と考え画像だけを扱うクラスを
scaffoldして解決しました。

Paperclipについては下記が詳しい。
http://www.mountposition.co.jp/blog/?p=114
http://www.cocoalife.net/category/programming/ruby/ruby-on-rails
http://www.matthewhutchinson.net/2010/10/25/editing-file-uploads-with-a-paperclip-processor

公開ディレクトリに置くのは嫌なのでDBに格納したいのだけども、とりあえず
動いてるので先に進みます。


class Image < ActiveRecord::Base
:
has_attached_file :image,
:styles => { :medium => "100x100>", :thumb => "32x32>" },
:path => ":rails_root/system/:attachment/:id/:styles.:extension"
:
end
と設定することで、ログには以下のように出ているようになっています。

SQL (0.1ms) BEGIN
[paperclip] identify -format %wx%h '/tmp/stream20110121-4777-16r2gn-0.JPG[0]' 2>/dev/null
[paperclip] convert '/tmp/stream20110121-4777-16r2gn-0.JPG[0]' -resize "32x32>" '/tmp/stream20110121-4777-16r2gn-020110121-4777-ia2kau-0' 2>/dev/null
[paperclip] identify -format %wx%h '/tmp/stream20110121-4777-16r2gn-0.JPG[0]' 2>/dev/null
[paperclip] convert '/tmp/stream20110121-4777-16r2gn-0.JPG[0]' -resize "100x100>" '/tmp/stream20110121-4777-16r2gn-020110121-4777-x6f4p2-0' 2>/dev/null
AREL (0.2ms) UPDATE `images` SET `image_updated_at` = '2011-01-21 08:19:34', `image_file_size` = 978349, `updated_at` = '2011-01-21 08:19:37', `image_file_name` = 'PC080042.JPG' WHERE (`images`.`id` = 9)
[paperclip] Saving attachments.
[paperclip] saving /var/www/html/hoge/system/images/thumbs/9.JPG
[paperclip] saving /var/www/html/hoge/system/images/mediums/9.JPG
[paperclip] saving /var/www/html/hoge/system/images/originals/9.JPG
SQL (1.8ms) COMMIT


と書いたのだけど、表示の際に困ったことになるので(なったw)、
Viewでは


<img src="/users/<%= @user.id %>/images/1/thumb.jpg" alt="画像" border="0">
<img src="/users/<%= @user.id %>/images/1/medium.jpg" alt="画像" border="0">
Modelでは

has_attached_file :image,
:styles => { :medium => "100x100>", :thumb => "32x32>" },
:path => ":rails_root/system/:attachment/:id/:styles/:basename.:extension"
Controllerでは

def thumb
if @user = User.authenticate(session[:login_user])
@image = Image.findByUserIdAndImageId(params)
image = image.split(/\?/)[0]
ext = (@image[:image_content_type]).split(/\//)[1]
thumb = ""
open(image).each_byte do |c|
thumb << c
end
send_data(thumb,
:type => @image[:image_content_type],
:filename => (@user[:loginId] + "_thumb." + ext))
end
end
とすることで、通常のユーザには見えない場所に置くことができるように
なりました。
アップロードされた画像ファイルは Rails_root/:app_name/system に置かれています。