diff --git a/README.md b/README.md index f862212..1b46378 100644 --- a/README.md +++ b/README.md @@ -63,12 +63,19 @@ When given a string, it interpolates the string with the following fields: * %f - first @@n1_length characters of number (configured through Phoner::Phone.n1_length), default is 3 (512) * %l - last characters of number (5486) * %x - the extension number +* %d{} - characters in brackets will only appear if extension is present ```ruby pn = Phoner::Phone.parse('+385915125486') pn.to_s # => "+385915125486" pn.format("%A/%f-%l") # => "091/512-5486" pn.format("+ %c (%a) %n") # => "+ 385 (91) 5125486" +pn.format("+ %c (%a) %n%d{ ext.}%x") # => "+ 385 (91) 5125486" +``` +```ruby +pn = Phoner::Phone.parse('+1-800-555-0125x443') +pn.format("%c (%a) %n") # => "1 (800) 5550125" +pn.format("%c (%a) %n%d{ ext.}%x") # => "1 (800) 5550125 ext.443" ``` When given a symbol it is used as a lookup for the format in the Phoner::Phone.named_formats hash. @@ -77,6 +84,7 @@ When given a symbol it is used as a lookup for the format in the Phoner::Pho pn.format(:europe) # => "+385 (0) 91 512 5486" pn.format(:us) # => "(234) 123-4567" pn.format(:default_with_extension) # => "+3851234567x143" + ``` You can add your own custom named formats like so: diff --git a/lib/phone.rb b/lib/phone.rb index e5169e9..6d79225 100644 --- a/lib/phone.rb +++ b/lib/phone.rb @@ -338,6 +338,8 @@ def format_number(fmt) # TODO: When we drop 1.8.7 we can pass the hash in as an arg to #gsub fmt.gsub(FORMAT_TOKENS) do |match| replacements[match.to_s] + end.gsub(/%d\{(.*?)\}/) do + extension.nil? ? '' : $1 end end end diff --git a/test/phone_test.rb b/test/phone_test.rb index 638f366..a678a9d 100644 --- a/test/phone_test.rb +++ b/test/phone_test.rb @@ -145,6 +145,18 @@ def test_format_with_symbol_specifier assert_equal pn.format(:europe), '+385 (0) 91 512 5486' end + def test_format_with_conditional_extension_with_extension + Phoner::Phone.default_country_code = nil + pn = Phoner::Phone.new '5125486', '191', '385', '242' + assert_equal pn.format('+ %c (%a) %n%d{ #}%x'), '+ 385 (191) 5125486 #242' + end + + def test_format_with_conditional_extension_without_extension + Phoner::Phone.default_country_code = nil + pn = Phoner::Phone.new '5125486', '191', '385' + assert_equal pn.format('+ %c (%a) %n%d{ #}%x'), '+ 385 (191) 5125486' + end + def test_validity assert true, Phoner::Phone.valid?("+17788827175") end