Forum: Ruby on Rails Problems with composed_of

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
1a9637acaccba514bf6c2cecf80c3f16?d=identicon&s=25 LeonB (Guest)
on 2007-05-05 12:10
(Received via mailing list)
Hi,

I'm having problems with composed_of

I have this two classes:

class Declaration < ActiveRecord::Base
  composed_of :amount, :class_name => "Currency", :mapping =>
%w(amount amount)
end

class Currency
  attr_accessor :round, :decimal, :amount

  def initialize(amount)
    self.amount = amount
    self.round = amount.to_i.to_s[0..-3]
    self.decimal = amount.to_i.to_s[-2..-1]
  end

end

What I want to do: I want "amount" of the declaration model to be an
object. I'm trying to execute the following;

>> declaration = Declaration.new
=> #<Declaration:0xb739f1b8 @attributes={"updated_at"=>nil,
"description"=>nil, "amount"=>nil, "user_id"=>nil, "created_at"=>nil},
@new_record=true>
>> declaration.amount = 12
NoMethodError: undefined method `amount' for 12:Fixnum
        from (eval):3:in `amount='
        from (irb):2
>>

I would like to be able to do:
declaration.amount = 1200
declaration.amount.cents() # or something like that)

What am I doing wrong?
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2007-05-05 12:51
(Received via mailing list)
LeonB wrote:

>     self.round = amount.to_i.to_s[0..-3]
>     self.decimal = amount.to_i.to_s[-2..-1]
>   end
>
> I would like to be able to do:
> declaration.amount = 1200

declaration.amount = Currency.new(1200)

--
We develop, watch us RoR, in numbers too big to ignore.
1a9637acaccba514bf6c2cecf80c3f16?d=identicon&s=25 LeonB (Guest)
on 2007-05-06 15:38
(Received via mailing list)
Thanks for the reply. But doing Currency.new() every time seems a bit
like a hassle.
1a9637acaccba514bf6c2cecf80c3f16?d=identicon&s=25 LeonB (Guest)
on 2007-05-06 22:05
(Received via mailing list)
Ah, added this tot the model:

  def amount=(amount)
    @amount = Currency.new(amount)
  end

that worked nicely.
This topic is locked and can not be replied to.