Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/phony_rails/string_extensions.rb
Instance Method Summary collapse
-
#phony_formatted(options = {}) ⇒ Object
Add a method to the String class so we can easily format phone numbers.
-
#phony_formatted!(options = {}) ⇒ Object
The bang method.
-
#phony_normalized(options = {}) ⇒ Object
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’.
Instance Method Details
#phony_formatted(options = {}) ⇒ Object
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)
25 26 27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/phony_rails/string_extensions.rb', line 25 def phony_formatted( = {}) raise ArgumentError, "Expected options to be a Hash, got #{.inspect}" unless .is_a?(Hash) = .dup normalize_country_code = .delete(:normalize) s, ext = PhonyRails.extract_extension(self) s = (normalize_country_code ? PhonyRails.normalize_number(s, default_country_code: normalize_country_code.to_s, add_plus: false) : s.gsub(/\D/, '')) return if s.blank? return if [:strict] && !Phony.plausible?(s) PhonyRails.format_extension(Phony.format(s, .reverse_merge(format: :national)), ext) rescue StandardError raise if [:raise] s end |
#phony_formatted!(options = {}) ⇒ Object
The bang method
40 41 42 43 |
# File 'lib/phony_rails/string_extensions.rb', line 40 def phony_formatted!( = {}) raise ArgumentError, 'The :strict options is only supported in the phony_formatted (non bang) method.' if [:strict] replace(phony_formatted()) end |
#phony_normalized(options = {}) ⇒ Object
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'
8 9 10 11 12 |
# File 'lib/phony_rails/string_extensions.rb', line 8 def phony_normalized( = {}) raise ArgumentError, "Expected options to be a Hash, got #{.inspect}" unless .is_a?(Hash) = .dup PhonyRails.normalize_number(self, ) end |