Posted almost 8 years ago. Visible to the public.

tel_to Rails helper for linking phone numbers

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.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for unsupported versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2).

Owner of this card:

Arne Hartherz
Last edit:
almost 8 years ago
by Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more