2022-02-03 08:37:38 +01:00
|
|
|
module LocalizeInput
|
|
|
|
extend ActiveSupport::Concern
|
|
|
|
|
2022-02-20 20:48:37 +01:00
|
|
|
def self.parse(input)
|
|
|
|
return input unless input.is_a? String
|
|
|
|
|
|
|
|
Rails.logger.debug { "Input: #{input.inspect}" }
|
2023-05-12 13:01:12 +02:00
|
|
|
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
|
2022-02-20 20:48:37 +01:00
|
|
|
input
|
2023-05-12 13:01:12 +02:00
|
|
|
rescue StandardError
|
2022-02-20 20:48:37 +01:00
|
|
|
Rails.logger.warn "Can't localize input: #{input}"
|
|
|
|
input
|
|
|
|
end
|
|
|
|
|
2022-02-03 08:37:38 +01:00
|
|
|
class_methods do
|
|
|
|
def localize_input_of(*attr_names)
|
|
|
|
attr_names.flatten.each do |attr|
|
|
|
|
define_method "#{attr}=" do |input|
|
2022-02-20 20:48:37 +01:00
|
|
|
self[attr] = LocalizeInput.parse(input)
|
2022-02-03 08:37:38 +01:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|