Archive for the ‘Ruby’ tag
Value Objects & RoR
Currently I’m working on my personal project, aiming to increase my Ruby On Rails skills. It’s quite a simple system for my dad’s company and one of the features is to register his clients. I started it out writing the Specs and as I’m new to the Ruby world, doubts started to pop inside my head. I was wondering how to use Value Objects ( Eric Evans definition, please! ) integrated with RoR, something I can do with Java as shown below:
public class Phone() {
private int code;
private int number;
....
}
public class Client() {
private String name;
private Phone home;
private Phone mobile;
....
}
Chatting with Carlos Villela, he advised me to take a look at composed_of feature, that it would help me get the solution for my problem. The final result is shown below. I’m definitely not used to the Ruby syntax yet, for me it’s still a bit confusing.
class Phone
attr_reader :code, :number
def initialize(code, number)
@code, @number = code, number
end
def ==(other)
code==other.code && number==other.number
end
end
class Client < ActiveRecord::Base
composed_of :home, :class_name => "Phone",
:mapping => [ %w(home_code code), %w(home_number number) ]
composed_of :mobile, :class_name => "Phone",
:mapping => [ %w(mob_code code), %w(mob_number number) ]
end