P
Pascal Ehlert
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?
Thank you
-- Pascal
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?
Thank you
-- Pascal