Skip to content

Instantly share code, notes, and snippets.

@paulmars
Last active November 18, 2015 00:44
Show Gist options
  • Select an option

  • Save paulmars/7f311c7d4cfab573f16d to your computer and use it in GitHub Desktop.

Select an option

Save paulmars/7f311c7d4cfab573f16d to your computer and use it in GitHub Desktop.
Rails Image Upload
module Tokenable
extend ActiveSupport::Concern
included do
before_validation :generate_token
validates :token, presence: true, uniqueness: true
end
protected
def generate_noise
SecureRandom.urlsafe_base64(nil, false).gsub(/[-_]+/,'').downcase
end
def generate_token
return if self.token.present?
random_token = self.generate_noise[0,4]
self.token = loop do
break random_token unless self.class.exists?(token: random_token)
random_token += self.generate_noise[0,2]
end
end
end
class GalleryImage < ActiveRecord::Base
include Tokenable
mount_uploader :image, DigestUploader
end
class DigestUploader < CarrierWave::Uploader::Base
include CarrierWave::MiniMagick
process :store_details
storage :fog
def store_dir
"gallery/#{model.token}"
end
def filename
"o.#{model.image.file.extension}"
end
def extension_white_list
%w(jpg jpeg gif png)
end
version :phone, :if => :resizable? do
process :resize_to_limit => [750, nil]
def full_filename(for_file = model.logo.file)
"p.#{model.image.file.extension}"
end
end
version :favorite, :if => :resizable? do
process :resize_to_fill => [300,300]
def full_filename(for_file = model.logo.file)
"f.#{model.image.file.extension}"
end
end
def resizable? picture
picture.content_type.index("gif").nil?
end
private
def store_details
if file && model
model.content_type = file.content_type if file.content_type
model.file_size = file.size
model.width, model.height = ::MiniMagick::Image.open(file.file)[:dimensions]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment