Ruby Money vs nil — aka undefined method `round’ for nil:NilClass

Problem
When using composed_of with Money you get this nice error when trying to get the money object while the cents column is nil.
Additionally Money.new(nil) does not work, neither do strings like Money.new(params[:cents]).

Solution
Overwrite the initializer to also accept nil and strings

# config/initializers/money.rb
require 'money'
class Money
  def initialize_with_default_currency(*args)
    args[0] = args[0].to_i if args[0].is_a?(String) or args[0].blank?
    args[1] ||= Money.default_currency
    initialize_without_default_currency(*args)
  end
  alias_method_chain :initialize, :default_currency
end
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s