Forum: Ruby on Rails Aggregation: problem with uninitialized composed_of object

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
1981f87f5be54f66e535d348ab07247b?d=identicon&s=25 Adriano (Guest)
on 2009-01-16 19:17
(Received via mailing list)

I'm getting this error:

>> p =
>> 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  => { |s| },
              :mapping    => [:price, :value]

class Money
  attr_reader :value

  def initialize(string)
    @value = BigDecimal(string.sub(/,/, '.'))

  def to_s
    Integer(@value * 100).to_s.sub(/(\d{2})$/, ',\1')

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?


A9426492837b45e637b517e81ab43f5f?d=identicon&s=25 Adriano Nagel (Guest)
on 2009-01-17 02:18
(Received via mailing list)
For the record...

On Jan 16, 4:17 pm, Adriano <> wrote:
> TypeError: wrong argument type String (expected Fixnum)


>   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(/,/, '.'))

This topic is locked and can not be replied to.