From bc5bc2d5ac6149f3cf16fa4bbc3127630b671ac0 Mon Sep 17 00:00:00 2001 From: Patrick Gansterer Date: Sun, 20 Feb 2022 20:48:37 +0100 Subject: [PATCH] Refactor LocalizeInput to reuse parse functionality --- .../financial_transactions_controller.rb | 2 +- app/models/concerns/localize_input.rb | 28 ++++++++++--------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/app/controllers/finance/financial_transactions_controller.rb b/app/controllers/finance/financial_transactions_controller.rb index 8b9d372d..930acebe 100644 --- a/app/controllers/finance/financial_transactions_controller.rb +++ b/app/controllers/finance/financial_transactions_controller.rb @@ -89,7 +89,7 @@ class Finance::FinancialTransactionsController < ApplicationController params[:financial_transactions].each do |trans| # ignore empty amount fields ... unless trans[:amount].blank? - amount = trans[:amount].to_f + amount = LocalizeInput.parse(trans[:amount]).to_f note = params[:note] ordergroup = Ordergroup.find(trans[:ordergroup_id]) if params[:set_balance] diff --git a/app/models/concerns/localize_input.rb b/app/models/concerns/localize_input.rb index 8198d7b2..cfb44a44 100644 --- a/app/models/concerns/localize_input.rb +++ b/app/models/concerns/localize_input.rb @@ -1,23 +1,25 @@ module LocalizeInput extend ActiveSupport::Concern + def self.parse(input) + return input unless input.is_a? String + + Rails.logger.debug { "Input: #{input.inspect}" } + separator = I18n.t("separator", scope: "number.format") + delimiter = I18n.t("delimiter", scope: "number.format") + input.gsub!(delimiter, "") if input.match(/\d+#{Regexp.escape(delimiter)}+\d+#{Regexp.escape(separator)}+\d+/) # Remove delimiter + input.gsub!(separator, ".") # Replace separator with db compatible character + input + rescue + Rails.logger.warn "Can't localize input: #{input}" + input + end + class_methods do def localize_input_of(*attr_names) attr_names.flatten.each do |attr| define_method "#{attr}=" do |input| - begin - if input.is_a? String - Rails.logger.debug "Input: #{input.inspect}" - separator = I18n.t("separator", :scope => "number.format") - delimiter = I18n.t("delimiter", :scope => "number.format") - input.gsub!(delimiter, "") if input.match(/\d+#{Regexp.escape(delimiter)}+\d+#{Regexp.escape(separator)}+\d+/) # Remove delimiter - input.gsub!(separator, ".") # Replace separator with db compatible character - end - self[attr] = input - rescue - Rails.logger.warn "Can't localize input: #{input}" - self[attr] = input - end + self[attr] = LocalizeInput.parse(input) end end end