Papeclipで画像ファイル向け汎用メソッドを定義するサンプル[Ruby]
paperclipでは画像ファイル以外も添付できる。 気をつけないと画像ファイル以外のObjectからも呼ばれる危険性がある。
画像ファイルに限定したUtilityメソッドを安全に定義するための例として以下の様な実装を考えてみた。
module ImageFileDecorator extend ActiveSupport::Concern module ClassMethods # Public # # Paperclipによって添付されたimageファイル向けのUtilityメソッドを追加するメソッド # # returns/raises section def activate_image_file_utils *images images.each{|image| # 画像ファイルの横幅、縦幅の配列を取得するメソッドを定義 define_method("#{image}_dimensions") { tmp_file = send(image).queued_for_write[:original] if tmp_file.present? geometry = Paperclip::Geometry.from_file(tmp_file) [geometry.width.to_i, geometry.height.to_i] end } # ... } end end end class SomeModle < ActiveRecord::Base # attributes # - iamge_file_name # - image_content_type # - image_file_size # - image_updated_at # - pdf_file_name # - pdf_content_type # - pdf_file_size # - pdf_updated_at has_attached_file :image, :pdf activate_image_file_utils :image end some_model = SomeModel.find_by(id: 1) some_model.respond_to?(:image_dimensions) # => true some_model.respond_to?(:pdf_dimensions) # => false
うーん、他に良い解法がありそうな気もする