Skip to content

Instantly share code, notes, and snippets.

@rjz
Created November 4, 2012 16:55
Show Gist options
  • Select an option

  • Save rjz/4012584 to your computer and use it in GitHub Desktop.

Select an option

Save rjz/4012584 to your computer and use it in GitHub Desktop.
Rails Twitter Intent Helper
# Demonstrate helper for rendering twitter intents
#
# Usage:
#
# Twitter::Intents.tweet(
# :text => 'Hello, world!',
# :via => 'rjzaworski',
# :url => 'https://gist.github.com/gists/4012584'
# )
#
# refer to https://dev.twitter.com/docs/intents
module Twitter
# Represent an intent
class Intent
# Assign an endpoint and options to this intent
def initialize(endpoint, opts)
@endpoint = endpoint
@opts = opts
end
# Render the intent according to the requested style.
# The style name will be used to call an appropriate
# rendering method, following +render_as_STYLE()+
def render(style)
params = []
@opts.each { |key, value| params << "#{key}=#{URI::encode(value)}" }
send("render_as_#{style}", "https://twitter.com/intent/#{@endpoint}?" + params.join('&')).html_safe
end
protected
# Provide default renderer
def render_as_default(intent)
caption = @opts.key?(:caption) ? @opts[:caption] : 'Tweet this'
'<a href="' + intent + '">' + caption + '</a>'
end
# Provide alternate "mini" renderer
# Renderers can be anything!
def render_as_share_mini(intent)
'<a href="' + intent + '"><i class="icon icon-twitter" style="background:url(/img/icons/16/twitter.png) 0 0;"></i> Twitter</a>'
end
end
# Expose builder methods for +Twitter::Intent+
module Intents
# tweet intent
def self.tweet(opts, style = 'default')
options = {
:url => '',
:via => '',
:text => '',
:hashtags => ''
}.merge(opts)
return Intent.new('tweet', opts).render(style)
end
# follow intent
def self.follow(opts, style = 'default')
options = {
:screen_name => '',
:user_id => ''
}.merge(opts)
return Intent.new('follow', opts).render(style)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment