instance method sms_to

Ruby on Rails 7.0.10

Since v6.1.7.10

Available in: v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

Signature

sms_to(phone_number, name = nil, html_options = {}, &block)

Creates an SMS anchor link tag to the specified phone_number. When the link is clicked, the default SMS messaging app is opened ready to send a message to the linked phone number. If the body option is specified, the contents of the message will be preset to body.

If name is not specified, phone_number will be used as the name of the link.

A country_code option is supported, which prepends a plus sign and the given country code to the linked phone number. For example, country_code: "01" will prepend +01 to the linked phone number.

Additional HTML attributes for the link can be passed via html_options.

Options

  • :country_code - Prepend the country code to the phone number.

  • :body - Preset the body of the message.

Examples

sms_to "5155555785"
# => <a href="sms:5155555785;">5155555785</a>

sms_to "5155555785", country_code: "01"
# => <a href="sms:+015155555785;">5155555785</a>

sms_to "5155555785", "Text me"
# => <a href="sms:5155555785;">Text me</a>

sms_to "5155555785", body: "I have a question about your product."
# => <a href="sms:5155555785;?body=I%20have%20a%20question%20about%20your%20product">5155555785</a>

You can use a block as well if your link target is hard to fit into the name parameter. ERB example:

<%= sms_to "5155555785" do %>
  <strong>Text me:</strong>
<% end %>
# => <a href="sms:5155555785;">
       <strong>Text me:</strong>
     </a>

Parameters

phone_number req
name opt = nil
html_options opt = {}
block block
Source
# File actionview/lib/action_view/helpers/url_helper.rb, line 665
      def sms_to(phone_number, name = nil, html_options = {}, &block)
        html_options, name = name, nil if name.is_a?(Hash)
        html_options = (html_options || {}).stringify_keys

        country_code = html_options.delete("country_code").presence
        country_code = country_code ? "+#{ERB::Util.url_encode(country_code)}" : ""

        body = html_options.delete("body").presence
        body = body ? "?&body=#{ERB::Util.url_encode(body)}" : ""

        encoded_phone_number = ERB::Util.url_encode(phone_number)
        html_options["href"] = "sms:#{country_code}#{encoded_phone_number};#{body}"

        content_tag("a", name || phone_number, html_options, &block)
      end

Defined in actionview/lib/action_view/helpers/url_helper.rb line 665 · View on GitHub · Improve this page · Find usages on GitHub

Defined in ActionView::Helpers::UrlHelper

Type at least 2 characters to search.

↑↓ navigate · open · esc close