Skip to content

Instantly share code, notes, and snippets.

@atsuya046
Last active August 29, 2015 14:17
Show Gist options
  • Save atsuya046/d44d6d16fd57ff6f61d7 to your computer and use it in GitHub Desktop.
Save atsuya046/d44d6d16fd57ff6f61d7 to your computer and use it in GitHub Desktop.
papeclipで画像ファイル向けのUtilityメソッドを定義するサンプル
# paperclipでは画像ファイル以外も添付できるので、気をつけないと画像ファイル以外のObjectからも呼ばれる危険性がある。
# 画像ファイルに限定したUtilityメソッドを安全に定義するための例として以下の様な実装を考えてみた。
module ImageFileDecorator
extend ActiveSupport::Concern
module ClassMethods
# Public
#
# Paperclipによって添付されたimageファイル向けのUtilityメソッドを追加するメソッド
#
# returns/raises section
def activate_image_file_utilities *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
activate_image_file_utilities: image
end
some_model = SomeModel.find_by(id: 1)
some_model.respond_to?(:image_dimensions)
# => true
some_model.respond_to?(:pdf_dimensions)
# => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment