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

Leave a comment