Created
April 17, 2011 20:19
-
-
Save jamescook/924431 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "bigdecimal" | |
# It would be nice if BigDecimal( BigDecimal("1") ) returned '1' as bigdecimal instead of an argument error, as it generally expects a String. | |
#I ran into this problem upgrading a project to rails3 from rails2 that was using the old mysql adapter. In the conversion, we switched to mysql2 which auto converts query results to ruby-land types, hence BigDecimal(sql_decimal_result_that_used_to_be_a_string) will now fail as the adapter returns a BigDecimal. | |
# The real world solution was to remove the BigDecimal wrapper around those sql queries, but the below was an interesting exercise nonetheless. | |
# BigDecimal("1") really means call a special global function 'BigDecimal' defined on Kernel. The C code is straight copy/pasta of BigDecimal.new :[ | |
# Make it go away | |
Kernel.send :remove_method, :BigDecimal | |
module Kernel | |
class << self | |
def BigDecimal_with_fix initial, digit=0 | |
if initial.is_a?(BigDecimal) | |
return initial | |
elsif initial.is_a?(Fixnum) | |
return BigDecimal.new initial.to_s, digit | |
end | |
BigDecimal.new initial, digit | |
end | |
alias_method :BigDecimal, :BigDecimal_with_fix | |
end | |
end | |
# Redefine the global BigDecimal function on Object and have it call our custom code above | |
class Object | |
class_eval do | |
def BigDecimal *args | |
Kernel.BigDecimal *args | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment