Created
March 20, 2013 22:13
-
-
Save swistak35/5209009 to your computer and use it in GitHub Desktop.
Decimals
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
params[:foo] = DecimalSupport.parse_model_decimals(params[:foo], Foo) |
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 DecimalSupport | |
def self.parse_model_decimals(hash, model, options = {}) | |
defaults = I18n.translate(:'number.format', locale: options[:locale], default: {}) | |
precision_defaults = I18n.translate(:'number.precision.format', locale: options[:locale], default: {}) | |
defaults = defaults.merge(precision_defaults) | |
options = options.reverse_merge(defaults) | |
hash.each do |field, value| | |
column = model.columns.find {|c| c.name == field.to_s} | |
hash[field] = if column.type == :decimal | |
self.parse_decimal(value, options) | |
else | |
value | |
end | |
end | |
hash | |
end | |
def self.parse_decimal(value, options = {}) | |
if value.blank? | |
"0.0" | |
else | |
separator_position = value.rindex(options[:separator]) | |
if separator_position.present? | |
int_part = value[0...separator_position] | |
frac_part = value[(separator_position+1)..-1] | |
int_part.gsub!(options[:delimiter], '') | |
[int_part, frac_part].join(".") | |
else | |
value | |
end | |
end | |
end | |
end |
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
ActionView::Helpers::FormBuilder.class_eval do | |
include ActionView::Helpers::NumberHelper | |
def decimal_number_field(field, options = {}) | |
value = object.send(field) | |
column = object.class.columns.find {|c| c.name == field.to_s} | |
new_options = { raise: true } | |
new_options[:precision] = column.try(:scale) | |
new_options[:separator] = options.delete(:separator) | |
new_options[:delimiter] = options.delete(:delimiter) | |
new_options[:significant] = options.delete(:significant) | |
new_options[:strip_insignificant_zeros] = options.delete(:strip_insignificant_zeros) | |
new_options[:raise] = true | |
new_options.delete_if {|k,v| v.nil? } | |
options[:value] = number_with_precision(value, new_options) | |
options[:class] = "#{options[:class]} decimal_number_field" | |
text_field(field, options) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment