Samstag, 12. Juli 2008

composed_of

class CurrencyRate < ActiveRecord::Base
composed_of :country_rate, :mapping => [%w(rate c_rate) , %w(currency c_currency)]
end

composed_of :value_object_name, :mapping =>
[%w(db_column_name_1 @instance_var_name_1)
%w(db_column_name_2 @instance_var_name_2)]

important: composed_of gives the class object CurrencyRate 2 new methods,
country_rate and country_rate=
the order of the mapping determines the order in which country_rate= receives its values and how the values will be mapped to the database table.


class CountryRate #this is the value object aggregated by CurrencyRate
attr_accessor :c_rate, :c_currency

def initialize(rate,currency="USD")
@c_rate, @c_currency=rate,currency
end
end

class CreateCurrencyRates < ActiveRecord::Migration #This is the table
def self.up
create_table :currency_rates do |t|
t.string :base_currency
t.string :currency
t.float :rate

t.timestamps
end
end

def self.down
drop_table :currency_rates
end
end

######### How it is used

cur=CurrencyRate.new(:base_currency =>"DKK")
cur.country_rate=CountryRate.new(12.4 , "YPN")
cur.save

######## What happens

cur=CurrencyRate.find(:first) # lets find a CurrencyRate object to change
# direct access methods have been stripped
cur.rate=123 # <- undefined method
cur.country_rate.rate=123 # <- no method error
cur.country_rate.c_rate=123 # <- can' modify frozen object

####The correct way to access is as follows

cur.base_currency="YPN"
cur.country_rate=CountryRate.new(345,"PLN")
cur.save # now the

#####before, the database looks like this

id base_currency rate currency
1 DKK 12.4 YPN

####after, it looks like this

id base_currency rate currency
1 YPN 345.0 PLN


Just for claritys sake.

CurrencyRate is a class with one instance var base_currency
CountryRate is a class with two instance vars c_rate and c_currency

with the composed_of method CountryRate has become a value object.
Value Objects: equality is determined by value - (represented by their value)
Entity Objects: equality is determined by identity - (represented by their primary keys)

Keine Kommentare: