westman2222
westman2222

Reputation: 683

Output integer as phone number format in view

I am trying to show show this as a formatted phone number like: xxx-xxx-xxxx instead of just a number string like it currently is ..any help would be great!

<% if @post.phone.present? %>
    <h4>Phone: <small> <%= @post.phone %><br></h4>
<% end %> 

Upvotes: 1

Views: 891

Answers (2)

victorkt
victorkt

Reputation: 14562

You can use number_to_phone helper, like this:

<% if @post.phone.present? %>
   <h4>Phone: <small> <%= number_to_phone @post.phone %><br></h4>
<% end %> 

By default, it formats the phone number as xxx-xxx-xxxx :

2.1.1 :009 > number_to_phone(1235551234)  
 => "123-555-1234" 
2.1.1 :010 > number_to_phone("1235551234")  
 => "123-555-1234" 

Upvotes: 2

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

Use the phone gem. https://github.com/carr/phone

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(:europe) # => "+385 (0) 91 512 5486"
pn.format(:us) # => "(234) 123-4567"
pn.format(:default_with_extension) # => "+3851234567x143"

Upvotes: 0

Related Questions