O'Reilly logo

Ruby Cookbook by Leonard Richardson, Lucas Carlson

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.17. Adding Hooks to Table Events

Problem

You want to run some code whenever a database row is added, updated, or deleted. For instance, you might want to send out email whenever a new blog post is created.

Solution

For Og, use the aspect-oriented features of Glue::Aspect. You can use its before and after methods to register code blocks that run before or after any Og method. The methods you're most likely to wrap are og_insert, og_update, and og_delete.

In the following code, I take the BlogPost class first defined in Recipe 13.12, and give its og_insert method an aspect that sends out email:

	require 'cookbook_dbconnect'
	require 'og'
	require 'glue/aspects'

	class BlogPost
	  property :title, :content, String
	  after :on => :og_insert do |post|
	    puts %{Sending email notification of new post "#{post.title}"}
	    # Actually send the email here…
	    end
	end

	og_connect
	post = BlogPost.new
	post.title = 'Robots are taking over'
	post.content = 'Think about it! When was the last time you saw another human?'
	post.save!
	# Sending email notification of new post "Robots are taking over"

This technique works with ActiveRecord as well (since aspect-oriented programming is a generic technique), but ActiveRecord defines two different approaches: callbacks and the ActiveRecord::Observer class.

Any ActiveRecord::Base subclass can define a number of callback methods: before_find, after_save, and so on. These methods run before or after the corresponding ActiveRecord methods. Here's an callback-based ActiveRecord implementation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required