Module: TwitterCards

Defined in:
lib/twitter_cards.rb,
lib/twitter_cards/version.rb

Defined Under Namespace

Classes: Object

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.extract(doc, opts = {}) ⇒ Hashie Object, false

Extracts Twitter Cards data from a parsed document.

Parameters:

  • uri (Nokogiri::HTML::Document)

    the nokogiri parsed document extract cards from.

  • opts (Hash) (defaults to: {})

    options to customize functionality

  • :strict (Hash)

    a customizable set of options

Returns:

  • (Hashie Object, false)

    a TwitterCards::Object if there is data to be found or false otherwise.



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/twitter_cards.rb', line 40

def self.extract(doc, opts = {})
  opts[:strict] ||= false

  page = TwitterCards::Object.new
  doc.css('meta').each do |m|
    if m.attribute('name') and m.attribute('name').to_s.match(/^twitter:(.+)$/i)
      property = $1        
    elsif m.attribute('property') and m.attribute('property').to_s.match(/^twitter:(.+)$/i) 
      property = $1                       
    end

    if property
      property.gsub!(/[-:]/,'_')
      page[property] = m.attribute('content').to_s unless page[property]
    end
  end

  return false if page.keys.empty?
  return false unless page.valid? if opts[:strict]
  page
end

.fetch(uri, opts = {}) ⇒ Hashie Object, false

Fetch Twitter Cards data from the specified URI with a HTTP GET request.

Parameters:

  • uri (String)

    the uri to fetch and extract cards from.

  • opts (Hash) (defaults to: {})

    options to customize functionality

  • :strict (Hash)

    a customizable set of options

Returns:

  • (Hashie Object, false)

    a TwitterCards::Object if there is data to be found or false otherwise.



15
16
17
18
19
# File 'lib/twitter_cards.rb', line 15

def self.fetch(uri, opts = {})
  parse(RestClient.get(uri).body, opts)
rescue RestClient::Exception, SocketError
  false
end

.parse(html, opts = {}) ⇒ Hashie Object, false

Parses HTML and extracts Twitter Cards data.

Parameters:

  • uri (String)

    the html text to parse and extract cards from.

  • opts (Hash) (defaults to: {})

    options to customize functionality

  • :strict (Hash)

    a customizable set of options

Returns:

  • (Hashie Object, false)

    a TwitterCards::Object if there is data to be found or false otherwise.



28
29
30
31
# File 'lib/twitter_cards.rb', line 28

def self.parse(html, opts = {})
  doc = Nokogiri::HTML.parse(html)
  extract(doc, opts)
end