Sha256: 873e214688eefa7ccfa8ea3ac84f50d03a7276c6d15e6d203304f93e32b0a8da

Contents?: true

Size: 1.46 KB

Versions: 7

Compression:

Stored size: 1.46 KB

Contents

# encoding: utf-8
module SPS
  module Converter
    def convert(*attributes, options)
      include InstanceMethods

      method_name = "convert_#{options[:to]}"
      unless InstanceMethods.method_defined?(method_name)
        raise ArgumentError.new("Converter '#{options[:to]}' does not exist!")
      end

      attributes.each do |attribute|
        define_method "#{attribute}=" do |value|
          instance_variable_set("@#{attribute}", send(method_name, value))
        end
      end
    end

    module InstanceMethods
      def convert_text(value)
        return unless value

        value.to_s.
          # Replace some special characters described as "Best practices" in Chapter 6.2 of this document:
          # http://www.europeanpaymentscouncil.eu/index.cfm/knowledge-bank/epc-documents/sepa-requirements-for-an-extended-character-set-unicode-subset-best-practices/
          gsub('€','E').
          gsub('@','(at)').
          gsub('_','-').

          # Replace linebreaks by spaces
          gsub(/\n+/,' ').

          # Remove all invalid characters
          gsub(/[^a-zA-Z0-9ÄÖÜäöüß&*$%\ \'\:\?\,\-\(\+\.\)\/]/, '').

          # Remove leading and trailing spaces
          strip
      end

      def convert_decimal(value)
        return unless value
        value = begin
          BigDecimal(value.to_s)
        rescue ArgumentError
        end

        if value && value.finite? && value > 0
          value.round(2)
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
sps_king-0.5.0 lib/sps_king/converter.rb
sps_king-0.4.0 lib/sps_king/converter.rb
sps_king-0.3.1 lib/sps_king/converter.rb
sps_king-0.3.0 lib/sps_king/converter.rb
sps_king-0.2.0 lib/sps_king/converter.rb
sps_king-0.1.1 lib/sps_king/converter.rb
sps_king-0.1.0 lib/sps_king/converter.rb