Posted almost 7 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:

Copy
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:

Copy
>> 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.

Copy
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:

Copy
>> 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.

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
almost 7 years ago
by Arne Hartherz
Attachments:
link_helper_spec.rb
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