From: Rick DeNatale Date: 2008-02-09T22:54:28+09:00 Subject: Re: Inheriting from / Delegating to Integer - Currency class implementation On 2/9/08, Pascal Ehlert wrote: > Howdy folks. > > I'm currently working on a Currency class which I'd like to behave > exactly like Integer with some additional methods like #to_currency and > and overridden #to_s method etc. > > My first approach was to inherit from Integer directly which failed, > because there is no constructor for this class. After some more > research I found the DelegateClass method which seemed to be exactly > what I need, however there was one major problem with it: Methods like > #+ and #- returned Integer, not Currency objects. So "(Currency.new(20) > + Currency.new(30)).class" evaled to Integer and my custom methods have > been gone. > > The latest approach was not to inherit at all but write the class from > scratch, carrying around a @value instance variable which stores an > Integer representation of the currency. > Unfortunately that idea didn't work to good either because I couldn't > add Currency objects to Fixnums anymore, "20 + Currency.new(30)" raised > a TypeError ("Currency can't be coerced into Fixnum"), although my > class implements a #to_i method. > > I actually like best the second way, using DelegateClass. > Are there any ways to make the calculation methods return a Currency > object then? > Or do you at least have an idea how to solve the problem with the > latest approach? class Currency attr_reader :base_value def initialize(value) @base_value = value end def +(other) Currency.new(@base_value + other.to_currency.base_value) end def to_currency self end def coerce(other) [self, other.to_currency] end end class Numeric def to_currency Currency.new(self) end end Currency.new(10) + Currency.new(5) # => # 10 + Currency.new(5) # => # HTH -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/