Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <tt>Phoner::Phone.named_formats</tt> hash.
Expand All @@ -77,6 +84,7 @@ When given a symbol it is used as a lookup for the format in the <tt>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:
Expand Down
2 changes: 2 additions & 0 deletions lib/phone.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions test/phone_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down