A little-known and very useful feature Rails brings to the table in terms of testing is a pair of callback hooks for Test::Unit::TestCase setup and teardown.

The callback chains were introduced as part of the move toward a custom ActiveSupport::TestCase, but all the functionality of ActiveSupport::TestCase is exposed to Test::Unit::TestCase if you’re running Rails.

Having these hooks exposed allows you to inject setup and teardown behavior without stepping on the toes of any individual test.

class Test::Unit::TestCase
  def self.does_not_perform_validations klass
    setup do
      @preserved_validations = klass.validate.clone
      klass.validate.clear
    end
    teardown do
      @preserved_validations.each do |validation|
        klass.validate << validation
      end
    end
  end
end

Obviously this example is a little contrived, but perhaps you see how this can be used.

class MarshmallowTest < Test::Unit::TestCase
  does_not_perform_validations Marshmallow
  …
end

Now with a single macro, we can inject setup and teardown behavior for a model. The same technique can be used to inject teardown hooks from within individual tests, but beware, hooks injected in this way need to remove themselves from the callback chain when executing, or else they’ll be executed for every subsequent test teardown.

module Foo
  def shared
    'Foo shared'
  end
 
  def foobar
    shared
  end
end
 
module Moo
  def shared
    'Moo shared'
  end
 
  def moobar
    shared
  end
end
 
class Wingnut
  include Moo
  include Foo
end
 
w = Wingnut.new
 
w.foobar # => "Foo shared"
w.moobar # => "Foo shared"

In the old days, we did this:

User.find(:all, :conditions => { :subscribed => true }, :order => 'created_at DESC' )

And then this:

User.find_all_by_subscribed(true, :order => 'created_at DESC' )

How about this?

User.for_subscribed(true).order_by('created_at DESC').find(:all)

Here’s the how!

class User < ActiveRecord::Base
  named_scope_for :subscribed
end

Whup-cha!

class ActiveRecord::Base
  def self.named_scope_for attribute
    named_scope "for_#{attribute}",
      lambda { |attribute_value| { :conditions => { attribute => attribute_value } } }
  end
 
  named_scope :order_by, Proc.new { |*attributes|
    raise ArgumentError, 'You must specify an attribute to order by' if attributes.blank?
    { :order => attributes.join(', ') }
  }
end

Check it out it here, or install using git.

git clone git://github.com/duncanbeevers/named_scope_for.git vendor/plugins/named_scope_for

When dealing with ActionScript’s ExternalInterface.addCallback the method to be exposed might not be immediately available. whenAvailable polls until a property shows up on a javascript object, at which point it invokes the provided callback.

function whenAvailable(availableObject, availableProperty, onAvailable) {
  if ('object' != typeof(availabilityCheckers)) {
    availabilityCheckers = {};
  }
 
  var checkAvailabilityFunction = function(){
    if('undefined' != typeof(availableObject[availableProperty])){
      checker = availabilityCheckers[checkerInterval];
      clearInterval(checker.interval);
      checker.onAvailable(availableObject, availableProperty, availableObject[availableProperty]);
    }
  };
 
  var checkerInterval = setInterval(checkAvailabilityFunction, 500);
 
  availabilityCheckers[checkerInterval] = {
    interval: checkerInterval,
    onAvailable: onAvailable
  }
}

Some of my co-workers like to use Notational Velocity to store sensitive information. Though a fine application, I’m partial to my existing tools and wanted something more general-purpose and flexible.

To that end, I set up a simple encrypted disk image and configured it to mount with a password prompt when I log on.

  1. Open Disk Utility and select New Image from the toolbar.

  2. Configure the Disk Image. I don’t have any big files to encrypt so I opted for the smallest (10MB) image size. Select an option from the Encryption drop-down.

  3. Set up a password for your disk image.

  4. In order to require password entry to open the disk image you’ll need to set up the permissions in Keychain Access.

  5. Under Access Control for the disk image Keychain entry, remove diskimages-helper from the list of programs always allowed to access the entry.

  6. In the Accounts Preference Pane, configure the disk image to mount on login.

Now simply select the mounted volume as the destination for files you want encrypted and sleep easy.

Nick Kallen’s named_scope allows you to create readable, powerful class-specific finder scopes.

One thing that might bite new users is how it operates in the Class context. Specifically, Named Scopes created in a parent class, even those using the lambda syntax, are scoped to the parent class.

For example, we might have a generic SQL operation that finds records whose date field falls within a certain range in a parent class, and simply allow any child classes to provide the range.

class HighScore
  named_scope :for_date, lambda { |time| { :conditions => { :date => time_range_for(time) } } }
end
 
class DailyHighScore < HighScore
  def self.time_range_for time
    (time.beginning_of_day)..(time.beginning_of_day + 1.day)
  end
end
 
class WeeklyHighScore < HighScore
  def self.time_range_for time
    (time.beginning_of_week)..(time.beginning_of_week + 1.week)
  end
end

Wouldn’t it be lovely if we could just rely on the subclass to complete the conditions? Unfortunately, since time_range_for is not defined in the HighScore class, this code will not not work.

The solution is to create individual Named Scopes on the child classes. However, instead of declaring unique Named Scopes, common behavior is isolated in the parent class by providing a Named Scope builder.

class HighScore
  def self.has_named_scope_for_time_range
    named_scope :for_date, lambda { |time| { :conditions => { :date => time_range_for(time) } } }
  end
end
 
class DailyHighScore < HighScore
  def self.time_range_for time
    (time.beginning_of_day)..(time.beginning_of_day + 1.day)
  end
 
  has_named_scope_for_time_range
end
 
class WeeklyHighScore < HighScore
  def self.time_range_for time
    (time.beginning_of_week)..(time.beginning_of_week + 1.week)
  end
 
  has_named_scope_for_time_range
end

Now all child classes using has_named_scope_for_time_range get a for_date Scope that works just the way they want. An additional advantage of this approach is that the parent class no longer has the extraneous for_date Named Scope.

UpdateRick Olson pointed out the overhead in accessing instance_values, and suggested instead using instance_variable_get.

Done!

Ruby’s attr_accessor is incredibly handy for wiring up your class’s banal getters and setters. If you’re wiring up some simple booleans this way though, wouldn’t you like to get the beauty of Ruby’s method punctuation?

I mean come on, we’re asking a question here.

The old way:

class Doyen
  attr_accessor :recondite
 
  def recondite?
    self.recondite
  end
 
end

Blah… Let’s tidy that up.

class Doyen
  bool_attr_accessor :recondite
end

Now our Doyen no longer has doyen.recondite, but simply doyen.recondite? and no visual clutter.

The implementation is simple:

class Module
  def bool_attr_accessor *args
    args.each do |arg|
      self.instance_eval do
 
        define_method("#{arg}=") do |value|
          instance_variable_set("@#{arg}", !!value)
        end
 
        define_method("#{arg}?") do
          instance_variable_get("@#{arg}")
        end
 
      end
    end
 
  end
end

Originally I used an attr_writer *args to simplify the setters, but I decided that since this function would always return a boolean, it would be better to do the conversion on the setter and let the getter simply return the pre-converted value.

Delete and return the first instance of a given object from an array.

class Array
  def delete_first(to_delete)
    self.each_with_index do |item, index|
      return delete_at(index) if item == to_delete
    end
    return nil
  end
end

The subject of cropping and resizing images comes up fairly often in the Rails community, with a number of tools out there to automate these manipulations.

When manipulating images, I like to use MiniMagick to keep the memory footprint of the application server itself small. Since MiniMagick just wraps the command-line convert and mogrify tools, special-casing your image resizer is as simple as modifying the flags passed to the underlying system command.

There are a number of resizing algorithms in use. Various approaches include maintaining the original image’s aspect ratio, cropping over-sized images, and padding resized images.

In order to achieve good fit an image may need to be both scaled and cropped. A well-fit image will maintain as much of the original image as possible while still conforming to the final target dimensions and aspect.

To illustrate the desired results, we’ll be manipulating the speakersitter image.
Original 300 × 586

Check out some examples of the various approaches to fixed-size output.

  1. With over-sized images, by far the simplest approach is the naive crop. Unfortunately, this fails us when the image is too small, and looks pretty terrible in most cases anyway.

    Cropped to 150 × 90

  2. Next up is the naive scale. This approach is nice in that it delivers consistent results no matter what the image’s original dimensions were. On the down side, this consistent behavior typically sucks.

    Scaled to 150 × 90

  3. Padding can be a nice way of getting generally good-looking output. A padding algorithm will scale an image maintaining its aspect ratio so that none of its dimensions is greater than the corresponding output dimension, and then will composite that scaled image onto the center of a blank image of the target dimensions. In this example, the checkerboard pattern represents the background image onto which the original image is composited. In real world usage, this image would be pure white or transparent.

    Scaled to 46 × 90, Padded to 150 × 90

  4. The good fit approach is similar to the padding approach, in that the source image is immediately scaled with a fixed aspect ratio. In the padding approach the image’s dimensions such that none is greater than its corresponding output dimension, both are constrained such that none is less than the output dimension. This guarantees that part of the source image will be cropped unless it is exactly the same aspect as the output dimensions.

    The scaled source image can be cropped according to one of nine different gravities. If your application deals primarily with portraits and face images, North gravity is typically the best.

    Perfect Fit 150 × 90 North Gravity

    For most other applications, including avatar and thumbnail generation, Center Gravity can be preferable.

    Perfect Fit 150 × 90 Center Gravity

Sadly, MiniMagick doesn’t support doing this all from the command line without a little pre-computation. We must sadly scale and then crop according to offsets we compute ourselves. Fortunately, I have already taken care of this for you!

I monkey-patched these changes directly into attachment_fu’s mini_magick_processor, but the calculations and generated commandline flags should serve you wherever you use MiniMagick.

module Technoweenie::AttachmentFu::Processors::MiniMagickProcessor
  GRAVITY_TYPES = [ :north_west, :north, :north_east, :east, :south_east, :south, :south_west, :west, :center ]
 
  def resize_and_crop_image(img, size, options = {})
    gravity = options[:gravity] || :center
    g = Geometry.from_s(size.to_s)
    img.opaque
 
    img_width, img_height = *(img[:dimensions].map { |d| d.to_f } )
    resize_string = ''
 
    # Resize image to minimize difference between actual dimension and target dimension
    if img_width / g.width < img_height / g.height
      resize_string = "#{g.width.to_i}x"
      resultant_width = g.width
      resultant_height = (img_height * (g.width / img_width))
    else
      resize_string = "x#{g.height.to_i}"
      resultant_width = (img_width * (g.height / img_height))
      resultant_height = g.height
    end
 
    width_offset, height_offset = crop_offsets_by_gravity(
      gravity,
      [ resultant_width, resultant_height ],
      [ g.width, g.height ] )
 
    img.combine_options do |i|
      i.args << '+matte'
      i.resize(resize_string)
      i.gravity('NorthWest')
      i.crop "#{g.width.to_i}x#{g.height.to_i}+#{width_offset}+#{height_offset}!"
    end
  end
 
  def crop_offsets_by_gravity gravity, original_dimensions, cropped_dimensions
    raise(ArgumentError, "Gravity must be one of #{GRAVITY_TYPES.inspect}") unless GRAVITY_TYPES.include?(gravity.to_sym)
    raise(ArgumentError, "Original dimensions must be supplied as a [ width, height ] array") unless original_dimensions.kind_of?(Enumerable) && original_dimensions.size == 2
    raise(ArgumentError, "Cropped dimensions must be supplied as a [ width, height ] array") unless cropped_dimensions.kind_of?(Enumerable) && cropped_dimensions.size == 2
    original_width, original_height = original_dimensions
    cropped_width, cropped_height = cropped_dimensions
    # No vertical offset for northern gravity
    vertical_offset = case gravity
      when :north_west, :north, :north_east then 0
      when :center, :east, :west then [ ((original_height - cropped_height) / 2.0).to_i, 0 ].max
      when :south_west, :south, :south_east then (original_height - cropped_height).to_i
    end
    horizontal_offset = case gravity
      when :north_west, :west, :south_west then 0
      when :center, :north, :south then [ ((original_width - cropped_width) / 2.0).to_i, 0 ].max
      when :north_east, :east, :south_east then (original_width - cropped_width).to_i
    end
    return [ horizontal_offset, vertical_offset ]
  end
end

Nick Kallen noted that the behavior of has_many_with_args can be accomplished using has_finder.

Too true!

Imagine a system in which Users send Whispers to one another. We would like to see Whispers scoped so that:

  • A User viewing their own Whispers should see all Whispers they have received

  • A User viewing another User’s Whispers should see only Whispers they themselves sent

With the clean chainable syntax provided by has_finder, this is straight-forward. We return associations directly (notice, no find calls) and isolate declaration of the scoping the behavior to the class affected by it.

class Whisper < ActiveRecord::Base
  has_finder :from, lambda { |sender| { :conditions => [ 'sender_id = ?', sender.id ] } }
end
 
class User < ActiveRecord::Base
  has_many :received_whispers, :foreign_key => 'recipient_id'
 
  def whispers_viewable_by user
    return whispers if self == user
    whispers.from(user)
  end
end

How expressive is that? Business rules are cleanly captured in the models and our associations stay so limber!

Thanks to Pat Maddox for turning me on to has_finder, and Nick Kallen for writing it.