Skip to content

Commit

Permalink
Refactor LocalizeInput to reuse parse functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
paroga committed May 27, 2022
1 parent 6a3636d commit bc5bc2d
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def create_collection
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]
Expand Down
28 changes: 15 additions & 13 deletions app/models/concerns/localize_input.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit bc5bc2d

Please sign in to comment.