Skip to content

Instantly share code, notes, and snippets.

@matheusvetor
Forked from kirs/avatar_uploader.rb
Last active December 16, 2015 18:21
Show Gist options
  • Save matheusvetor/5477404 to your computer and use it in GitHub Desktop.
Save matheusvetor/5477404 to your computer and use it in GitHub Desktop.
class Banner < ActiveRecord::Base
attr_accessor :image_width, :image_height
mount_uploader :image, ImageUploader
validate :check_dimensions
def check_dimensions
if !self.image_cache.nil?
errors.add :image, "Dimensions of uploaded avatar should be not less than 150x150 pixels." if self.upload_width < 150 || self.upload_height < 150
end
end
end
# encoding: utf-8
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
# Choose what kind of storage to use for this uploader:
storage :file
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
"/uploads/missing/#{model.class.to_s.underscore}/#{version_name}.png"
end
# for image size validation
# fetching dimensions in uploader, validating it in model
before :cache, :capture_size_before_cache # callback, example here: http://goo.gl/9VGHI
def capture_size_before_cache(new_file)
if model.upload_width.nil? || model.upload_height.nil?
model.upload_width, model.upload_height = `identify -format "%wx %h" #{new_file.path}`.split(/x/).map { |dim| dim.to_i }
end
end
# resizing uploads
process :resize_to_fill => [148, 148]
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg png)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment