Created
December 15, 2008 13:10
-
-
Save dnadlinger/35948 to your computer and use it in GitHub Desktop.
This file contains 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
module CustomNumberFormat | |
DECIMAL_SEPARATOR = ',' | |
module ActiveRecord | |
def self.included( base ) | |
base.send :extend, ClassMethods | |
base.class_eval do | |
class << self | |
alias_method_chain :define_write_method, :conversion | |
end | |
end | |
end | |
module ClassMethods | |
def define_write_method_with_conversion( attr_name ) | |
if [ :float, :decimal ].include? columns_hash[ attr_name.to_s ].type | |
method_definition = <<-END_OF_EVAL | |
def #{ attr_name }=( raw_value ) | |
if raw_value.class == String | |
processed_value = raw_value.tr( '#{ CustomNumberFormat::DECIMAL_SEPARATOR }', '.' ) | |
if processed_value.to_d.to_s == processed_value | |
raw_value = processed_value | |
end | |
end | |
write_attribute( '#{ attr_name }', raw_value ) | |
end | |
END_OF_EVAL | |
evaluate_attribute_method attr_name, method_definition, "#{ attr_name }=" | |
else | |
define_write_method_without_conversion( attr_name ) | |
end | |
end | |
end | |
end | |
module InstanceTag | |
def self.included( base ) | |
base.send :extend, ClassMethods | |
base.class_eval do | |
class << self | |
alias_method_chain :value_before_type_cast, :conversion | |
end | |
end | |
end | |
module ClassMethods | |
def value_before_type_cast_with_conversion( object, method_name ) | |
raw_value = value_before_type_cast_without_conversion( object, method_name ) | |
casted_value = value( object, method_name ) | |
if [ Float, BigDecimal ].include?( casted_value.class ) && casted_value.to_s == raw_value | |
raw_value = raw_value.tr( '.', CustomNumberFormat::DECIMAL_SEPARATOR ) | |
end | |
return raw_value | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send( :include, CustomNumberFormat::ActiveRecord ) | |
ActionView::Helpers::InstanceTag.send( :include, CustomNumberFormat::InstanceTag ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment