class TwitterEmbed::Tweet

This class provides static functionalities for crawling twitter

Public Class Methods

html_str(tweet_id,*args) click to toggle source

Crawl the embed's HTML string of twitter

@param tweet_id [String] @param *args [object] @return [String]

@example

TwitterEmbed.html_str('1234567890') #=> "<ul><li>foo</li><li>bar</li></ul>"
# File lib/twitter_embed.rb, line 21
def self.html_str(tweet_id,*args)
  return nil if tweet_id.nil? || tweet_id.to_s.empty?
  opt={}
  opt=args[0] unless args.nil? || args.empty?
  options={
    lang: 'en',
    theme: 'light'
  }.
  merge(opt).
  merge({callback: "__twttr.callbacks.cb0", ids: tweet_id, suppress_response_codes: true})
  json={}
  domains=[
    "https://cdn.syndication.twimg.com",
    "https://syndication.twitter.com"
    ]
  domain_ctr=0
  while json.empty? && domain_ctr<domains.length
    #url="#{domains[domain_ctr]}/tweets.json?callback=__twttr.callbacks.cb0&ids=#{tweet_id}&lang=#{options[:lang]}&suppress_response_codes=true&theme=#{options[:theme]}"
    url="#{domains[domain_ctr]}/tweets.json"
    uri=URI.parse(url)
    uri.query=URI.encode_www_form( options )
    jsonp=Net::HTTP.get(uri)  
    str="{#{jsonp[/{(.*?)}/m, 1]}}"
    json=JSON.parse(str)
    domain_ctr+=1
  end
  html=nil
  html="<div class='twitter_embed_#{options[:theme]}'><div data-twitter-event-id='0' class='SandboxRoot ' style='position: relative;'>#{json.values.first}</div></div>" if json.any?
  return html
end
is_exists?(url) click to toggle source

Check if a twitter's post exist

@param url [String] @return [Boolean]

@example

TwitterEmbed.is_exists('https://twitter.com/rails/status/1240688751082221568') #=> true
# File lib/twitter_embed.rb, line 59
def self.is_exists?(url)
  return nil if url.nil? || url.to_s.empty?
  begin
    uri = URI("https://publish.twitter.com/oembed?url=#{CGI.escape(url)}&partner=&hide_thread=false")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    request = Net::HTTP::Get.new(uri)
    request["cache-control"] = 'no-cache'
    response = http.request(request)
    return true if response.code == "200"
    return false if response.code == "404"
    return nil
  rescue
    nil
  end
end