Skip to content

Commit

Permalink
Add validations before parsing actual source.
Browse files Browse the repository at this point in the history
  • Loading branch information
jcouture committed Sep 9, 2017
1 parent 71dea58 commit 28761d4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 3 deletions.
17 changes: 14 additions & 3 deletions lib/ogp/open_graph.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@
REQUIRED_ATTRIBUTES = %w(title type image url)

module OGP
class MissingAttributeError < StandardError
end

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

def initialize(source)
if source.nil? || source.empty?
raise ArgumentError.new('`source` cannot be nil or empty.')
end

if !source.include?('</html>')
raise MalformedSourceError
end

document = Oga.parse_html(source)
check_required_attributes(document)
parse_required_attributes(document)
Expand Down Expand Up @@ -39,4 +44,10 @@ def attribute_exists(document, name)
document.at_xpath("boolean(//head/meta[@property='og:#{name}'])")
end
end

class MissingAttributeError < StandardError
end

class MalformedSourceError < StandardError
end
end
18 changes: 18 additions & 0 deletions spec/lib/open_graph_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,5 +21,23 @@
expect{OGP::OpenGraph.new(content)}.to raise_error(OGP::MissingAttributeError)
end
end

context 'with nil source' do
it 'should raise an error' do
expect{OGP::OpenGraph.new(nil)}.to raise_error(ArgumentError)
end
end

context 'with empty source' do
it 'should raise an error' do
expect{OGP::OpenGraph.new('')}.to raise_error(ArgumentError)
end
end

context 'with malformed source' do
it 'should raise an error' do
expect{OGP::OpenGraph.new('Lorem ipsum dolor sit amet, consectetur adipiscing elit.')}.to raise_error(OGP::MalformedSourceError)
end
end
end
end

0 comments on commit 28761d4

Please sign in to comment.