Cropping image to aspect ratio with ImageMagick in Rails

I wanted to crop image in paperclip to some aspec ratio so that cropped image will use full width or height of original image.

A little bit math

It is simple to see that if croping is “wider” than original image, it must crop top and bottom of image and use full width. Otherwise, if cropping is “taller” than original image, it crops left and right while using full image height. This can be luckilly computed simply like this:
Let r_c is ratio of width:height of desired cropped image and r_i is ratio of original image.
If r_c > r_i (wider) then cropped image should have width = original_width and height = original_width / r_c
Otherwise, if r_c <= r_c (taller) then it should crop to width = original_height * r_c and height = original_height.
Problem is that it needs to know aspect ratio of original image. Retrieving that information somehow before hand is quite complicated and ineffective moreover since ImageMagick always know it. Can’t it do that computation by its own? ImageMagick never stops surprising me, yes, it can do that. Let’s look on it:

Convert options

It’s Ruby syntax, but it should be understandable :)

Example

Original image:
Chucky-Childs-Play
With ratio = 2 (width = 2* height):
chucky_crop2
With ratio = 0.5 (height = 2* width):
chucky_crop05