Open Classes

August 14th, 2007

This is really a beginner sample for those who wish that a certain Ruby class had X functionality. Instead of complaining about the lack of something, add it in yourself. Check this out.

I needed to take a Floating point number used as a monetary amount and convert it to “cents” (from dollars) to send for payment processing. I could use the really cool Money Gem, but that was a bit more than I really needed (vendor everything). So, I just opened up the Float class and added my own method:

1
2
3
4
5
class Float
  def to_cents
    self * 100
  end
end

That extends the Float class so that you can do 100.21.to_cents. You can then convert it to an integer if you wanted.

That is how easy it is to extend an existing class with Ruby or Rails – just open it up and add your method(s).

1 Response to “Open Classes”

  1. Joe Martinez Says:

    Be careful with this one – those money libraries exist because ruby’s float to integer operations are not always correct.

Sorry, comments are closed for this article.