Skip to content

Instantly share code, notes, and snippets.

@janko
Created October 31, 2013 22:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save janko/7257974 to your computer and use it in GitHub Desktop.
Save janko/7257974 to your computer and use it in GitHub Desktop.
Paperclip vs CarrierWave
class ImageQuestion < TextQuestion
store :data, accessors: [:image]
mount_uploader :image, ImageUploader
validates :image, download: true, processing: true
end
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
resize_to_limit nil, 800
version :resized do
resize_to_limit nil, 250
end
end
require "active_support/core_ext/numeric/bytes"
require "active_support/inflector/transliterate"
require "uri"
class ImageQuestion < TextQuestion
store :data,
accessors [:image_file_name, :image_content_type,
:image_file_size, :image_updated_at, :image_size]
has_attached_file :image, styles: {resized: "x250>"},
whiny: false
validates_attachment :image,
presence: {if: -> { [image_url, image_file].all?(&:blank?) }},
content_type: {content_type: ["image/jpeg", "image/gif", "image/png"], allow_blank: true},
size: {in: 0..1.megabyte}
validate :validate_image_url
attr_reader :image_url
def image_url=(url)
begin
@image_url = url
self.image = URI.parse(url)
rescue
self.image = nil
end if url.present?
end
attr_reader :image_file
def image_file=(file)
begin
@image_file = file
self.image = SanitizedFile.new(file)
rescue
self.image = nil
end if file.present?
end
private
def validate_image_url
if image_url.present? and image.blank?
errors.add(:image_url, :invalid)
end
end
class SanitizedFile < SimpleDelegator
include ActiveSupport::Inflector
# Because Paperclip chooses the adapter for uploaded files
# by looking at the class name
def self.name
"UploadedFile"
end
def original_filename
transliterate(__getobj__.original_filename)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment