When putting phone numbers into web pages, you should use tel:
links so smartphone users can click those numbers to call someone.
Here is a small helper method that you can use to simplify this:
def tel_to(text)
groups = text.to_s.scan(/(?:^\+)?\d+/)
link_to text, "tel:#{groups.join '-'}"
end
This will allow you to use human-readable numbers and get clean links:
>> tel_to '(01234) 555 6789'
=> <a href="tel:01234-555-6789">(01234) 555 6789</a>
^
>> tel_to '+1 555 123-456'
=> +1 555 123-456
If you have user-provided phone numbers, you may want to use the following version which also strips the leading zero of an area code (sometimes used when combining international and local numbers, see example below) as the called number should not include that zero.
def tel_to(text)
groups = text.to_s.scan(/(?:^\+)?\d+/)
if groups.size > 1 && groups[0][0] == '+'
# remove leading 0 in area code if this is an international number
groups[1] = groups[1][1..-1] if groups[1][0] == '0'
groups.delete_at(1) if groups[1].size == 0 # remove if it was only a 0
end
link_to text, "tel:#{groups.join '-'}"
end
It works on phone numbers like these:
>> tel_to '+1 (0)555 123-456'
=> <a href="tel:+1-555-123-456">+1 (0)555 123-456</a>
Attached you will also find a spec that goes along with the latter version.
Posted by Arne Hartherz to makandra dev (2014-11-27 14:08)