gitastic
gitastic

Reputation: 526

Escape # in Rails link_to, Twitter Share link

I'm trying to include an anchored article link in a Twitter share link dynamically with Rails link_to method:

<%= link_to "http://twitter.com/home?status=Check Out #{article.title} link.com/#{article.title.parameterize}" do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

The Twitter link share content outputs to:

Check Out ARTICLE TITLE link.com/ARTICLE-TITLE.

The thing is I want to add a # character before ARTICLE-TITLE, as it is an anchor link in my view. I just can't seem to get the # to escape properly. Is this even possible?

Upvotes: 2

Views: 667

Answers (2)

Jordan Running
Jordan Running

Reputation: 106137

In general it's a bad idea to build URLs with string concatenation—especially when you need to do something like put a URL in a query parameter of another URL.

To create correctly-encoded query parameters, use Rails' handy Hash#to_query method.

Let's take it from the inside out.

# Build the article URL
article_base_url = 'http://example.com/path'
article_url_hash = article.title.parameterize # => "my-article"
article_url = "#{article_base_url}##{article_url_hash}"
# => "http://example.com/path#my-article"

# Next, build the query string for the tweet URL
tweet_url_query = {
  status: "Check out #{article.title} #{article_url}"
}.to_query
# => "status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"

# Finally, build the tweet URL:
base_tweet_url = 'https://twitter.com/home'
tweet_url = "#{base_tweet_url}?#{tweet_url_query}"
# => "https://twitter.com/home?status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"
<%= link_to tweet_url do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

As perhaps you've already guessed, it's probably best to put this all in a helper:

ARTICLE_BASE_URL = 'http://example.com/'
TWEET_BASE_URL = 'http://twitter.com/home'

def tweet_url(title) 
  query = { status: tweet_text(title) }.to_query
  "#{TWEET_BASE_URL}?#{query}"
end

def tweet_text(title)
  "Check out #{title} #{article_url(title)}"
end

def article_url(title)
  "#{ARTICLE_BASE_URL}##{title.parameterize}"
end
<%= link_to tweet_url(article.title) do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

(You could, of course, reduce the above to a single two-line helper at the expense of readability and testability, but it would be a mistake.)

Upvotes: 0

gitastic
gitastic

Reputation: 526

%23 = # (in a Twitter share link).

ex. link.com/%23#{article.title.parameterize}

Looks like it's rendered as a hashtag (#thattookwaytoolongtofigureout #ihopethishelpssomeone)

Upvotes: 1

Related Questions