annealer annealer

gabriel gironda will have his revenge on seattle

Callbacks got refactored to ActiveSupport in Rails 2.1

Written on Monday, December 22, 2008

Chalk this up to something I never actually noticed until fairly recently. Callbacks got refactored out of ActiveRecord. I’ve ended up ghetto-implementing similar functionality before, and this does everything I could want it to. Here’s a trite example:

    module Playable
      def self.included(base)
        base.send(:include, ActiveSupport::Callbacks)
        base.define_callbacks(:before_play, :after_play)
      end

      def play
        run_callbacks(:before_play)
        yield
        run_callbacks(:after_play)
      end
    end

    class Track
      include Playable

      before_play { puts "About to play" }
      after_play :post_play_message

      def play
        super do
          puts "Playing"
        end
      end

    private

      def post_play_message
        puts "Done playing"
      end
    end


    >> Track.new.play
    About to play
    Playing
    Done playing
    

Waiting for Validations to finally follow suit and not be so AR-specific. There’s like two or three different implementations of an Errors object in Rails now, last I checked.

blog comments powered by Disqus

Annealer, a Jekyll powered blog by Gabriel Gironda.