ラベル paperclip の投稿を表示しています。 すべての投稿を表示
ラベル paperclip の投稿を表示しています。 すべての投稿を表示

2010/08/05

Paperclip を Rails 3 + Windows で動かすニャンコ

一日ハマッタので備忘録


今まで動いていたアプリを 2.3.8 から Rails 3.0.0beta4 にアップグレードしようとしたときのこと。
参考までに、今回の Gemfile
gem 'rmagick', :require => 'RMagick' 
gem "aws-s3", ">= 0.6.2",:require => "aws/s3"
gem "paperclip", ">= 2.3.3", :git => "git://github.com/thoughtbot/paperclip.git"

ところが、Paperclip が動かない。。。。 Image C:/Users/Me/AppData/Local/Temp/stream,4508,0.jpg is not recognized by the 'identify' command. だそうな。 identify (ImageMagick) が見つからないらしいので、チェックする。
$ which identify
/c/Program Files/ImageMagick-6.5.6-Q8/identify
こちらに対処法があったので、その通りに config/development.rb に追加
Paperclip.options[:command_path] = "/c/Program Files/ImageMagick-6.5.6-Q8/"
ところが undefined method `exitstatus' for nil:NilClass と。。。orz
/c/Program Files/ImageMagick-6.5.6-Q8/identify -format %wx%h "C:/Users/Me/AppData/Local/Temp/stream,5880,0.jpg[0]"
をアクセスしようとして、エラっている模様。じゃあ、コマンドプロムプトでマニュアル実行してみる。
> "/c/Program Files/ImageMagick-6.5.6-Q8/identify" -format %wx%h "C:/Users/Me/AppData/Local/Temp/stream,5880,0.jpg[0]"
> 指定されたパスが見つかりません。
なるほど。でも windows 風だとOK。
>"c:\Program Files\ImageMagick-6.5.6-Q8\identify" -format %wx%h "C:/Users/Me/Ap
pData/Local/Temp/stream,5880,0.jpg"
> 500x499 
なので、config/development.rb を次のように編集
Paperclip.options[:command_path] = "c:\\Program Files\\ImageMagick-6.5.6-Q8\\"
なおった!!ばんざ~い!

あと、念のためにこちらのスレッドにある変更も・・・
bundler の gem ディレクトリの各ファイルを編集(僕の場合は C:\Users\Me\.bundle\ruby\1.8\bundler\gems\paperclip-XXX-master\lib\paperclip)
因みに、インストールに失敗した別のバージョンの Paperclip gem が残っていてエラっていたこともあるので、綺麗にするように。 command_line.rb
    def shell_quote(string)
      return "" if string.nil? or string.blank?
      # string.split("'").map{|m| "'#{m}'" }.join("\\'")
      string.split("'").map{|m| "\"#{m}\"" }.join("\\'") 
    end
thumbnail.rb
    def transformation_command
      scale, crop = @current_geometry.transformation_to(@target_geometry, crop?)
      trans = []
     # trans << "-resize" << "'#{scale}'" unless scale.nil? || scale.empty?
     # trans << "-crop" << "'#{crop}'" << "+repage" if crop
       trans << "-resize" << "\"#{scale}\"" unless scale.nil? || scale.empty?
       trans << "-crop" << "\"#{crop}\"" << "+repage" if crop
      trans
    end

2010/9/2 Hosoku


It turns out adding this would be enough. Create a file initializers/paperclip.rb with the following contents.

if RUBY_PLATFORM == 'i386-mingw32'
  module Paperclip
    def self.quote_command_options(*options)
      options.map do |option|
        option.split("\"").map{|m| "\"#{m}\"" }.join("\\\"")
      end
    end
  end
end

2010/01/16

Ruby でファイルの存在をチェック

ローカルにあるファイル
if File.exist?(path)
...
end

リモートのファイル
require 'open-uri' # environments.rb に入れちゃう
begin
  if open(URI.parse(path))
    # ファイルが存在したら実行
  end
rescue => deadmeat
  if deadmeat.message =~/somestring like 403/ 
  # (Errno::ENOENT, OpenURI::HTTPError, etc...)などの exception を表示しない
  # ファイルが存在しなかったらやること
  end
end

2010/01/04

Paperclip と Amazon S3 でファイルを保存する

オンラインショップのサーバー要領がちょっとキツクなったので、画像データを Amazon S3 を使って保存してみょーと思い立つ。
ざっくり説明しますと、Amazon S3が外部ストーレージサービス。データをやり取りした分だけ課金されます。1GBで15円ほどなので、安くは無いけど、いろんなメリットを考えると高くもない。とりあえずテストしてみることに決定~。

まず、Amazon S3 に登録

S3 のデータを見るには『S3Fox』が便利

Firefox のプラグイン『S3Fox』を使うと、FTPクライアント風にAmazon S3の中がみれるよ。

Paperclip 設定の変更

以前、Paperclip の使い方についてメモりましたが、そこからちょいと手を加えます。 environment.rb に aws gem を追加
config.gem "aws-s3", :lib => "aws/s3"
(require する際に require = "aws/s3" とする場合は上のように、 :lib => "aws/s3" を加えて記述) この後、rake gems:install を実行するのを忘れずに。 config/s3.yml を作成
access_key_id: ABCD...
secret_access_key: xYz...
キーとシークレットはここから。 モデルの変更
 #通常バージョン
 has_attached_file :image,
   :styles => {:s => "150x150>", :m =>"320x320>", :l => "500x500>"},
   :url  => "/assets/products/:id/p_:style.:basename.:extension",
   :path => ":rails_root/public/assets/products/:id/p_:style.:basename.:extension"

 #↓S3 バージョン
 has_attached_file :image,
   :styles => {:s => "150x150>", :m =>"320x320>", :l => "500x500>"},
   :storage => :s3,
   :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
   :path => "products/:id/:style.:extension",
   :url  => ":s3_domain_url",
   :bucket => S3_BUCKET #S3_BUCKET は production/environment.rb development/environment.rb で定義

:s3_domain_url だと http://mybucket.s3.amazonaws.com/products/16152/l.jpg のようになる。
因みに、上で指定した bucket をあらかじめ作っておく必要があるのですー↓ この場合、S3Fox で作成。 これで準備はOK。さっそくアップロードしてみると。。。 入ってる!感激~

Paperclip で画像アップロード

ファイルや画像を簡単にアップロードできるプラグイン Paperclip の紹介。
http://github.com/thoughtbot/paperclip/tree/master

最初からテーブルに含める場合

      # migration ファイルに以下を追加
      t.string    :image_file_name, :image_content_type
      t.integer   :image_file_size
      t.datetime  :image_updated_at
      t.string    :image_remote_url
最後の image_remote_url は基本的には必要ないが、URLから画像アップロードしたいので、今回は追加しておく。

既存のテーブルに追加する場合

class AddImageColumnsToProducts < ActiveRecord::Migration
    def self.up
      add_column :products, :image_file_name,    :string
      add_column :products, :image_content_type, :string
      add_column :products, :image_file_size,    :integer
      add_column :products, :image_updated_at,   :datetime
    end

    def self.down
      remove_column :products, :image_file_name
      remove_column :products, :image_content_type
      remove_column :products, :image_file_size
      remove_column :products, :image_updated_at
    end
end

モデルの設定

  has_attached_file :image, 
    :styles => {:s => "150x150>", :m =>"320x320>", :l => "500x500>"},
    :url  => "/assets/products/:id/p_:style.:basename.:extension",
    :path => ":rails_root/public/assets/products/:id/p_:style.:basename.:extension"  
URLからのアップロードを可能にする場合は次も追加

  # ====================================
  # Paper Clip upload from url
  # ====================================
  attr_accessor :image_url    
  before_validation :download_remote_image, :if => :image_url_provided?
  validates_presence_of :image_remote_url, :if => :image_url_provided?, :message => 'is invalid or inaccessible'

  private
 
  def image_url_provided?
    !self.image_url.blank?
  end
 
  def download_remote_image
    self.image = do_download_remote_image
    self.image_remote_url = image_url
  end
 
  def do_download_remote_image
    io = open(URI.parse(image_url))
    def io.original_filename; base_uri.path.split('/').last; end
    io.original_filename.blank? ? nil : io
    rescue # catch url errors with validations instead of exceptions (Errno::ENOENT, OpenURI::HTTPError, etc...)
  end
フォーム
<% form_for ([:admin, @page]), :html => {:multipart => true } do |f| %>
  <%= f.file_field(:image) %>
  ...or provide a URL: <%= f.text_field :image_url %>
<% end %>
表示
<%= image_tag @foobar.image.url(:m) if @foobar.image? %>