# Aggregation: problem with uninitialized composed\_of object

**URL:** <https://www.ruby-forum.com/t/aggregation-problem-with-uninitialized-composed-of-object/157940>\
**Category:** Rails\
**Created:** [January 16, 2009, 7:17pm UTC](https://www.ruby-forum.com/t/aggregation-problem-with-uninitialized-composed-of-object/157940 "2009-01-16T19:17:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Adriano](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c37758/32.png) [@Adriano](https://www.ruby-forum.com/u/Adriano)\
**Post date:** [January 16, 2009, 7:17pm UTC](https://www.ruby-forum.com/t/aggregation-problem-with-uninitialized-composed-of-object/157940/1 "2009-01-16T19:17:55Z")

</div>

Hi,

I’m getting this error:

> > p = Plan.new  
> > p.amount  
> > TypeError: wrong argument type String (expected Fixnum)

Apparently this happens because the aggregation isn’t initialized.  
Here’s the code:

class Plan \< ActiveRecord::Base  
composed\_of :amount,  
:class\_name =\> “Money”,  
:converter =\> Proc.new { |s| Money.new(s) },  
:mapping =\> [:price, :value]  
end

class Money  
attr\_reader :value

def initialize(string)  
@value = BigDecimal(string.sub(/,/, ‘.’))  
end

def to\_s  
Integer(@value \* 100).to\_s.sub(/(\d{2})$/, ‘,\1’)  
end  
end

I would like to hide the aggregation from controllers…

There’s the after\_initialization callback where I could (try to)  
initialize the value object if it is nil…

I wonder what’s the proper way to deal with this situation?

Thanks,

–  
Adriano

---

<div class="post-metadata">

**Author:** ![Adriano](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/c37758/32.png) [@Adriano](https://www.ruby-forum.com/u/Adriano)\
**Post date:** [January 17, 2009, 2:18am UTC](https://www.ruby-forum.com/t/aggregation-problem-with-uninitialized-composed-of-object/157940/2 "2009-01-17T02:18:39Z")

</div>

For the record…

On Jan 16, 4:17 pm, Adriano [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> TypeError: wrong argument type String (expected Fixnum)

[snip]

> def initialize(string)  
> @value = BigDecimal(string.sub(/,/, ‘.’))  
> end

The problem was that value object can be initialized with a string  
(from the form) or with a number (from the db). Thus initialize should  
be changed, eg:

def initialize(value)  
@value = BigDecimal(value.to\_s(/,/, ‘.’))  
end

–  
Adriano
