Skip to content

Instantly share code, notes, and snippets.

@rondale-sc
Created March 22, 2012 05:34
Show Gist options
  • Select an option

  • Save rondale-sc/2156432 to your computer and use it in GitHub Desktop.

Select an option

Save rondale-sc/2156432 to your computer and use it in GitHub Desktop.
make-the-most-of-your-tweet
<a href="https://twitter.com/share" class="twitter-share-button"
data-count="vertical"
data-via="rondale_sc">Tweet</a>
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
class Article < ActiveRecord::Base
before_save :populate_short_url
def populate_short_url
self.short_url = get_shortened_url
end
def get_shortened_url
http = Net::HTTP.new("www.googleapis.com", 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.ca_file = File.join(Rails.root, "lib", "cacert.pem")
key = File.read(File.join(Rails.root, "lib", "google_api.txt")).strip
params = {'longUrl' => get_article_url }.to_json # self.url is your article slug
resp = http.post("/urlshortener/v1/url?key=#{key}", params, {'Content-Type' => 'application/json'})
body = JSON.parse(resp.body)
if resp.code.to_i == 200
@short_url = body["id"]
else
error = body["error"]
raise "Error: #{error["code"]} : #{error["message"]}"
end
end
def get_article_url
"YOUR_ROOT_URL" + self.url
end
end
# app/views/_tweet_button.html.erb
<a href="https://twitter.com/share" class="twitter-share-button"
data-url="<%= @article.short_url %>"
data-counturl="<%= request.url %>"
data-count="vertical"
data-via="rondale_sc">Tweet</a>
# in app/view/articles/show
<% content_for :head do %>
<%= content_tag("title", @article.title) %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment