Thursday, May 14, 2009

Shaping Models in ruby on rails

Whenever a new team member enters to any enhancement project, from technical perspective, he tries to understand the already developed code. Code comprehension may become difficult if there is no proper documentation. There can be many models with different relationships defined amongst themselves. Won't it be good to have some sort of diagrammatic representation of the Model relationships ? It will certainly be very helpful for the development and support teams to understand the application in technical perspective.

Let's develop small and simple ruby code to construct a diagrammatic representation
of the Model (Active Record) relationships (Model in M-V-C architecture) in any Ruby on Rails application. (We will follow KISS principle - Keep it simple and Succinct ! :-)

Active Record is an implementation of the object-relational mapping (ORM) pattern by the same name as described by Martin Fowler:

"An object that wraps a row in a database table or view, encapsulates
the database access, and adds domain logic on that data."



Active Record supports three types of relationship between tables:
(1) one-to-one
(2) one-to-many
(3) many-to-many.
You indicate these relationships by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.

There is a tool called 'Gvedit' (graphviz-2.20.2.exe) (http://www.graphviz.org/) which generates Directed and Undirected graphs. It accepts a dot file in specific format and it generates directed graphs free of cost ! :-) Why not use this tool ?

We can use the reflections for findling all associations of a Model.
http://api.rubyonrails.com/classes/ActiveRecord/Reflection/ClassMethods.html

Here is the utility which can be run from the rails application root and generates simple text file with the represention that the dot file requires for creating graphs. It looks for all the model classes under app/models directory.



It generates a simple text file as below :-

digraph model_relationship {
Asset -> DbFile [label=belongs_to]
Asset -> Thumbnail [label=has_many]
Category -> Child [label=has_many]
Category -> Content [label=has_and_belongs_to_many]
Category -> Parent [label=belongs_to]
Content -> Category [label=has_and_belongs_to_many]
Content -> Asset [label=belongs_to]
}


Save this as a .dot file. Open this file in Gvedit and run to generate the graph.

Here is a sample graph generated out of Gvedit :-



We can thus get a picture of all the model relationships in a typical ruby on rails application !

No comments:

Post a Comment