public
Description: A small Rails plugin for denormalizing attributes
Homepage: http://www.greenisgood.co.uk
Clone URL: git://github.com/mza/denormalizer.git
name age message
file LICENSE Loading commit data...
file README.textile
file Rakefile Wed Sep 03 05:41:12 -0700 2008 Initial plugin commit. [Matt Wood]
file init.rb
file install.rb
directory lib/
directory tasks/
directory test/
file uninstall.rb
README.textile

The Denormalizer

The Denormalizer extends ActiveRecord to allow for easy denormalization of attributes (real and computed) from one model to another.

Installation

Those rolling on Edge Rails can grab the plugin directly from the git repository:


./script/plugin install http://github.com/mza/denormalizer

Otherwise, clone the plugin in to the vendor/plugins folder to get started:


git clone --depth 1 git://github.com/mza/denormalizer.git vendor/plugins/denormalizer

Denormalizing

The Denormalizer arranges for attributes on one model to be saved as an attribute on a related model. This allows for faster queries,
since relationship trees don’t have to be fully loaded to retrieve the values. It can also save the results of a model’s method to the
database, again, to prevent multiple queries and heavy requests.

Denormalizing attributes

To denormalize standard, Active Record attributes from one model, first add the fields to the destination model.


	add_column :person_name
	add_column :person_age

By convention, The Denormalizer uses database fields prefixed with the source model’s singular name. Once the fields are in place, add the following to the class definition of the source model.


	class Person << ActiveRecord::Base
		has_many :addresses
 		denormalizes :name, :to => :addresses
 		denormalizes :age, :to => :addresses
	end
 

Pulling denormalized attributes

Above, The Denormalizer pushes fields from one source model to another. It can also pull attributes from a related object. The value is pulled when the object is saved to the database.

	
		class Address << ActiveRecord::Base
			belongs_to :person
		 	denormalizes :name, :from => :person
		  	denormalizes :key, :from => :person
		 	denormalizes :family_id, :from => :person
		end
	

Caching expensive methods

Methods that perform expensive lookups or computation can save their state to the model, again for faster lookups without having to query . Similar to Rails’ own counter cache, but more flexible.

	
		class Workflow << ActiveRecord::Base
			denormalizes :complete, :using => :complete?
		
			def complete?
				-- expensive --
			end					
		end
	

Feedback

Feedback is always welcome: matt.wood@sanger.ac.uk

License

This plugin is open source, and distributed under the BSD licence.