Class: TwitterEmbed::Tweet

Inherits:
Rails::Engine
  • Object
show all
Defined in:
lib/twitter_embed.rb

Overview

This class provides static functionalities for crawling twitter

Class Method Summary collapse

Class Method Details

.html_str(tweet_id, *args) ⇒ String

Crawl the embed’s HTML string of twitter

Examples:

TwitterEmbed.html_str('1234567890') #=> "<ul><li>foo</li><li>bar</li></ul>"

Parameters:

  • tweet_id (String)
  • *args (object)

Returns:

  • (String)


21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# 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) ⇒ Boolean

Check if a twitter’s post exist

Examples:

TwitterEmbed.is_exists('https://twitter.com/rails/status/1240688751082221568') #=> true

Parameters:

  • url (String)

Returns:

  • (Boolean)


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# 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