Thursday, July 10, 2008

Rails composed_of

Initially, I had the difficulty in understanding the composed_of.
It is very simple. It is used to associate the value object to the class (Newbie's, please note that the object is value object, not the active record object). Let's say an example we used in our project.

We have the FilterField class and SortField class. If you notice the common thing in both the classes you will come to know both are field classes. Right?

Why don't we have the seperate class for Field and associate it to FilterField class and SortField class. This will help us to group the field related attributes in Field class, sorting related attributes in SortField class and filter related attributes in FilterField class.

class Field
attr_reader :class_name
attr_reader :attribute_name
def initialize (class_name, attribute_name)
@class_name = class_name
@attribute_name = attribute_name
end
end


class SortField < ActiveRecord::Base
composed_of :query_field, :class_name=>'Field',
:mapping=>[%w(class_name class_name), %w(attribute_name attribute_name)]
end

class FilterField< ActiveRecord::Base
composed_of :query_field, :class_name=>'Field',
:mapping=>[%w(class_name class_name), %w(attribute_name attribute_name)]
end

SortField object can be created like below:

field => Field.new(:class_name=>'Court', :attribute_name=> 'Court_Name')
SortField.new(:query_field => field, :sorting_order => 'Ascending')

No comments: