Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding a strict boolean option to allow for partial parsing.

  • Loading branch information...
commit 7ea499f640687d797b546d1896e2f3f8b8825e18 1 parent be85cf9
@mbleigh mbleigh authored
Showing with 17 additions and 4 deletions.
  1. +8 −4 lib/opengraph.rb
  2. +9 −0 spec/opengraph_spec.rb
View
12 lib/opengraph.rb
@@ -6,13 +6,16 @@ module OpenGraph
# Fetch Open Graph data from the specified URI. Makes an
# HTTP GET request and returns an OpenGraph::Object if there
# is data to be found or <tt>false</tt> if there isn't.
- def self.fetch(uri)
- parse(RestClient.get(uri).body)
+ #
+ # Pass <tt>false</tt> for the second argument if you want to
+ # see invalid (i.e. missing a required attribute) data.
+ def self.fetch(uri, strict = true)
+ parse(RestClient.get(uri).body, strict)
rescue RestClient::Exception, SocketError
false
end
- def self.parse(html)
+ def self.parse(html, strict = true)
doc = Nokogiri::HTML.parse(html)
page = OpenGraph::Object.new
doc.css('meta').each do |m|
@@ -20,7 +23,8 @@ def self.parse(html)
page[$1.gsub('-','_')] = m.attribute('content').to_s
end
end
- return false unless page.valid?
+ return false if page.keys.empty?
+ return false unless page.valid? if strict
page
end
View
9 spec/opengraph_spec.rb
@@ -2,15 +2,24 @@
describe OpenGraph do
let(:rotten){ File.open(File.dirname(__FILE__) + '/examples/rottentomatoes.html').read }
+ let(:partial){ File.open(File.dirname(__FILE__) + '/examples/partial.html').read }
describe '.parse' do
it 'should return false if there isnt valid Open Graph info' do
OpenGraph.parse("").should be_false
+ OpenGraph.parse(partial).should be_false
end
it 'should otherwise return an OpenGraph::Object' do
OpenGraph.parse(rotten).should be_kind_of(OpenGraph::Object)
end
+
+ context ' without strict mode' do
+ subject{ OpenGraph.parse(partial, false) }
+
+ it { should_not be_false }
+ it { subject.title.should == 'Partialized' }
+ end
end
describe '.fetch' do
Please sign in to comment.
Something went wrong with that request. Please try again.