Skip to content

Instantly share code, notes, and snippets.

@DAddYE
Created December 30, 2011 22:57
Show Gist options
  • Save DAddYE/1541912 to your computer and use it in GitHub Desktop.
Save DAddYE/1541912 to your computer and use it in GitHub Desktop.

Revisions

  1. DAddYE created this gist Dec 30, 2011.
    49 changes: 49 additions & 0 deletions image_uploader.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    class ImageUploader < CarrierWave::Uploader::Base
    include CarrierWave::MiniMagick
    storage :file

    def thumb(size)
    begun_at = Time.now
    size.gsub!(/#/, '!')
    uploader = Class.new(self.class)
    uploader.versions.clear
    uploader.version_names = [size]
    img = uploader.new
    img.retrieve_from_store!(identifier)
    cached = File.join(CarrierWave.root, img.url)
    unless File.exist?(cached)
    img.cache!(self)
    img.send(:original_filename=, original_filename)
    size = size.split('x').map(&:to_i)
    resizer = case size
    when /[!#]/ then :resize_to_fit
    # add more like when />/ then ...
    else :resize_to_fill
    end
    img.send(resizer, *size)
    img.store!
    logger.debug 'RESIZE', begun_at, img.store_path
    end
    img
    end

    def store_dir
    'uploads'
    end

    def cache_dir
    Padrino.root('tmp/uploads')
    end

    def extension_white_list
    %w[jpg jpeg gif png]
    end

    def filename
    Digest::MD5.hexdigest(original_filename) << File.extname(original_filename) if original_filename
    end

    def default_url
    '/images/no-image.png'
    end
    end
    13 changes: 13 additions & 0 deletions test.out
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,13 @@
    >> i = ImageUploader.new
    => #<ImageUploader:0x1044314f8 @model=nil, @mounted_as=nil>
    >> i.download!('http://a1.twimg.com/profile_images/682283839/PadrinoLogo_reasonably_small.jpg')
    => [:process!, :assign_parent_cache_id, :cache_versions!]
    >> i.store!
    => [:store_versions!]
    >> i.url
    => "/uploads/35c40bbe3a9170e2901165990c34a173.jpg"
    >> i.thumb('100x100').url
    DEBUG - RESIZE (0.1124ms) uploads/100x100_35c40bbe3a9170e2901165990c34a173.jpg
    => "/uploads/100x100_35c40bbe3a9170e2901165990c34a173.jpg"
    >> i.thumb('100x100').url
    => "/uploads/100x100_35c40bbe3a9170e2901165990c34a173.jpg"