From 3115b735ea46c0f4cc4cfc14584a23fd9dc043b7 Mon Sep 17 00:00:00 2001 From: Jim Jones Date: Tue, 18 Jun 2019 12:10:16 -0500 Subject: Helper method to create an sms link - when clicked it opens the phone/desktop's messaging client with the phone number and optional body value prepopulated. --- actionview/lib/action_view/helpers/url_helper.rb | 48 ++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'actionview/lib/action_view/helpers/url_helper.rb') diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb index df83dff681..97ebb850d0 100644 --- a/actionview/lib/action_view/helpers/url_helper.rb +++ b/actionview/lib/action_view/helpers/url_helper.rb @@ -571,6 +571,54 @@ module ActionView end end + # Creates an sms anchor link tag to the specified +phone_number+, which is + # also used as the name of the link unless +name+ is specified. Additional + # HTML attributes for the link can be passed in +html_options+. + # + # When clicked, an sms message is prepopulated with the passed phone number + # and optional +body+ value. + # + # +sms_to+ has a +body+ option for customizing the sms message itself by + # passing special keys to +html_options+. + # + # ==== Options + # * :body - Preset the body of the email. + # + # ==== Examples + # sms_to "5155555785" + # # => 5155555785 + # + # sms_to "5155555785", "Text me" + # # => Text me + # + # sms_to "5155555785", "Text me", + # subject: "Hello Jim I have a question about your product." + # # => Text me + # + # 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 %> + # Text me: + # <% end %> + # # => + # Text me: + # + def sms_to(phone_number, name = nil, html_options = {}, &block) + html_options, name = name, nil if block_given? + html_options = (html_options || {}).stringify_keys + + extras = %w{ body }.map! { |item| + option = html_options.delete(item).presence || next + "#{item.dasherize}=#{ERB::Util.url_encode(option)}" + }.compact + extras = extras.empty? ? "" : "?&" + extras.join("&") + + encoded_phone_number = ERB::Util.url_encode(phone_number) + html_options["href"] = "sms:#{encoded_phone_number};#{extras}" + + content_tag("a", name || phone_number, html_options, &block) + end + private def convert_options_to_data_attributes(options, html_options) if html_options -- cgit v1.2.3