Running with Ruby

Tag: ImageMagick

Ruby: Dragonfly gem – auto-orient for all the images

Dragonfly is an awesome image/asset management tool. It is great because of many reasons, but what I love the most, is how it handles thumbnails. You don’t need to specify sizes, or anything else in the models in which you use it. Instead every type of thumbnail can be generated “on the fly”, the first time you access it. For that reason, the original image (by default) is always stored. Unfortunately by default, it will not be auto-oriented based on the picture Exif data. Luckily there’s an easy way out. In your Dragonfly model you need to include an after_assign block with an auto orient command and you are ready to go!

class Picture < ActiveRecord::Base
  extend Dragonfly::Model

  dragonfly_accessor :image do
    after_assign do |attachment|
      # Auto orient all the images - so they will look as they should
      attachment.convert! '-auto-orient'
    end
  end
end

After that all of your images (and all the thumbnails – since you change the original file) will be auto-oriented.

Paperclip and Rspec: Stubbing Paperclip/ImageMagick to make specs run faster, but with image resolution validation

I always test my Paperclip stuff. Mostly because quite often, I need to ensure proper images resolution or other image-based conditions. Unfortunately, it takes some time, mostly because ImageMagick is performing resource consuming operations. Each resolution test needs to get valid image to determine width and height. After that, Paperclip will try to create all the thumbs and save them. This takes a lot of time! Luckily there’s a Quickerclip that stubs Paperclip methods, allowing it to run faster. There’s one small issue with this code: it stubs the image, so there’s no way to test resolution validations. In order to make it work, but without any additional callbacks and without images converting, we need to stub two things:

First the Paperclip.run method:

# We stub some Paperclip methods - so it won't call shell slow commands
# This allows us to speedup paperclip tests 3-5x times.
module Paperclip
  def self.run cmd, params = "", expected_outcodes = 0
    cmd == 'convert' ? nil : super
  end
end

This will ignore convert command, so thumbnails won’t be created on save.

Also we need to stub the Paperclip::Attachment.post_process:

class Paperclip::Attachment
  def post_process
  end
end

Don’t forget to add this to your spec_helper or test_helper file!

After that, your tests/specs should run 3-5x times faster (it depends on how heavily you app is Paperclip based.

UPDATE FOR PAPERCLIP > 3.5.2
For Paperclip newer than 3.5.2 please use code presented below:

module Paperclip
  def self.run cmd, arguments = "", interpolation_values = {}, local_options = {}
    cmd == 'convert' ? nil : super
  end
end

class Paperclip::Attachment
  def post_process
  end
end

Copyright © 2018 Running with Ruby

Theme by Anders NorenUp ↑