Sha256: 88cb42e37888a07daf7fc7cb69bcf34572e8526bab846390b8aee8cca7a890e5

Contents?: true

Size: 1.81 KB

Versions: 5

Compression:

Stored size: 1.81 KB

Contents

  class String

    # Usage:
    #   "+31 (0)30 1234 123".phony_normalized # => '+31301234123'
    #   "(0)30 1234 123".phony_normalized # => '301234123'
    #   "(0)30 1234 123".phony_normalized(country_code: 'NL') # => '301234123'
    def phony_normalized(options = {})
      raise ArgumentError, "Expected options to be a Hash, got #{options.inspect}" if not options.is_a?(Hash)
      options = options.dup
      PhonyRails.normalize_number(self, options)
    end

    # Add a method to the String class so we can easily format phone numbers.
    # This enables:
    #   "31612341234".phony_formatted # => '06 12341234'
    #   "31612341234".phony_formatted(:spaces => '-') # => '06-12341234'
    # To first normalize a String use:
    #   "010-12341234".phony_formatted(:normalize => :NL)
    # To return nil when a number is not correct (checked using Phony.plausible?) use
    #   "010-12341234".phony_formatted(strict: true)
    # When an error occurs during conversion it will return the original String.
    # To raise an error use:
    #   "somestring".phone_formatted(raise: true)
    def phony_formatted(options = {})
      raise ArgumentError, "Expected options to be a Hash, got #{options.inspect}" if not options.is_a?(Hash)
      options = options.dup
      normalize_country_code = options.delete(:normalize)
      s = (normalize_country_code ? PhonyRails.normalize_number(self, :default_country_code => normalize_country_code.to_s, :add_plus => false) : self.gsub(/\D/, ''))
      return if s.blank?
      return if options[:strict] && !Phony.plausible?(s)
      Phony.format(s, options.reverse_merge(:format => :national))
    rescue
      if options[:raise]
        raise
      else
        s
      end
    end

    # The bang method
    def phony_formatted!(options = {})
      replace(self.phony_formatted(options))
    end

  end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
phony_rails-0.12.10 lib/phony_rails/string_extensions.rb
phony_rails-0.12.9 lib/phony_rails/string_extensions.rb
phony_rails-0.12.8 lib/phony_rails/string_extensions.rb
phony_rails-0.12.7 lib/phony_rails/string_extensions.rb
phony_rails-0.12.6 lib/phony_rails/string_extensions.rb