Posted about 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.

Once an application no longer requires constant development, it needs periodic maintenance for stable and secure operation. makandra offers monthly maintenance contracts that let you focus on your business while we make sure the lights stay on.

Owner of this card:

Avatar
Arne Hartherz
Last edit:
about 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