Refactor LocalizeInput to reuse parse functionality

This commit is contained in:
Patrick Gansterer 2022-02-20 20:48:37 +01:00
parent 6a3636d8cb
commit bc5bc2d5ac
2 changed files with 16 additions and 14 deletions

View File

@ -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]

View File

@ -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