Skip to content

Commit

Permalink
Validate the presence of required attributes.
Browse files Browse the repository at this point in the history
  • Loading branch information
jcouture committed Sep 9, 2017
1 parent 023ce7d commit 71dea58
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 1 deletion.
16 changes: 16 additions & 0 deletions lib/ogp/open_graph.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,28 @@
REQUIRED_ATTRIBUTES = %w(title type image url)

module OGP
class MissingAttributeError < StandardError
end

class OpenGraph
attr_accessor :title, :type, :image, :url

def initialize(source)
document = Oga.parse_html(source)
check_required_attributes(document)
parse_required_attributes(document)
end

private

def check_required_attributes(document)
REQUIRED_ATTRIBUTES.each do |attribute_name|
if !attribute_exists(document, attribute_name)
raise MissingAttributeError.new("Missing required attribute: #{attribute_name}")
end
end
end

def parse_required_attributes(document)
REQUIRED_ATTRIBUTES.each do |attribute_name|
instance_variable_set("@#{attribute_name}", parse_attribute(document, attribute_name))
Expand All @@ -22,5 +34,9 @@ def parse_required_attributes(document)
def parse_attribute(document, name)
document.at_xpath("//head/meta[@property='og:#{name}']").get('content')
end

def attribute_exists(document, name)
document.at_xpath("boolean(//head/meta[@property='og:#{name}'])")
end
end
end
11 changes: 10 additions & 1 deletion spec/lib/open_graph_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,23 @@
describe OGP::OpenGraph do
describe '#initialize' do
context 'with strictly the required attributes' do
it 'should parse attributes properly' do
it 'should create a proper OpenGraph object' do
content = File.read("#{File.dirname(__FILE__)}/../view/required_attributes.html")
open_graph = OGP::OpenGraph.new(content)

expect(open_graph.title).to eql('The Rock')
expect(open_graph.type).to eql('video.movie')
expect(open_graph.url).to eql('http://www.imdb.com/title/tt0117500/')
expect(open_graph.image).to eql('http://ia.media-imdb.com/images/rock.jpg')
end
end

context 'with missing one of the required attributes' do
it 'should raise an error' do
content = File.read("#{File.dirname(__FILE__)}/../view/missing_required_attributes.html")

expect{OGP::OpenGraph.new(content)}.to raise_error(OGP::MissingAttributeError)
end
end
end
end
11 changes: 11 additions & 0 deletions spec/view/missing_required_attributes.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta content="The Rock" property="og:title">
<meta content="video.movie" property="og:type">
<meta content="http://www.imdb.com/title/tt0117500/" property="og:url">
<title></title>
</head>
<body>
</body>
</html>

0 comments on commit 71dea58

Please sign in to comment.