Skip to content

The ImageScience Gets Done and You Make a Neat Gun.

I do write about the most exciting things.

Right so – ImageScience is a neat little ruby library for working with images without going through the drama, memory leaks and general hassle of using the full fat ruby image library Rmagick.

Image Science comes with the ability to produce a square thumbnail and a relational thumbnail. It doesn’t, however, come with a nice way of generating a ‘best fit’ thumbnail that will maintain aspect ratio, guarantee size and look alright most of the time. To save you some time, dear reader, I’ve done the googling, the code borrowing and the cleanup and come up with this:

The following method will allow you to give a target width and a target height get yielded back a thumbnail suitable for most occasions.

class ImageScience
   def cropped_thumb(target_width,target_height)
      aspect = target_width.to_f / target_height.to_f
      ih, iw = height, width
      w, h = (ih * aspect), (iw / aspect)
      w = [iw, w].min.to_i
      h = [ih, h].min.to_i
      self.with_crop( (iw-w)/2, (ih-h)/2, (iw+w)/2, (ih+h)/2) {|crop|
        crop.resize(target_width, target_height){|thumb|
          yield thumb
        }
      }
    end
end

And it looks like:

Categories: Uncategorized.

Tags: ,

Better Postcode Generation with Faker

Right then, my first blog post – again. One must start as he means to go on.

Recently I had the unhappy task of morphing some rather crusty and bloated fixtures into slim and beautiful factories. Part of this involved using the fantastic faker library to generate postcodes.

Unfortunately for me our models use a somewhat stricter regex for matching postcodes than the ‘format only’ postcode regex that we all know and love: the more aggressive regex ensures the letters Q, V and X are kept well away from the first position as well as enforcing other, even less interesting, rules.

Since faker generates postcodes in a fairly straightforward way – ignoring all the more subtle rules – those postcodes occasionally caused our validations to fail.

This seemed like a nice opportunity to patch faker so it’d generate more plausible postcodes – so I did.

Generate stricter postcodes like so:

require 'faker'
#strict postcode
Faker::Address.uk_postcode(:strict => true)

#or use the good old fashion generate
Faker::Address.uk_postcode

Categories: Uncategorized.

Tags: , ,