From f002061aaac6a267e76f610feb32cba319ac23c9 Mon Sep 17 00:00:00 2001 From: Yorick Peterse Date: Thu, 7 Aug 2014 21:10:01 +0200 Subject: [PATCH] Extra type validation for XML::Element options. --- lib/oga.rb | 2 +- lib/oga/xml/element.rb | 33 +++++++++++++++++++++++++++------ spec/oga/xml/element_spec.rb | 8 +++++++- 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/lib/oga.rb b/lib/oga.rb index bbaf0f0..f7e8fa4 100644 --- a/lib/oga.rb +++ b/lib/oga.rb @@ -17,7 +17,6 @@ end #:nocov: require_relative 'oga/xml/node' -require_relative 'oga/xml/element' require_relative 'oga/xml/document' require_relative 'oga/xml/text' require_relative 'oga/xml/comment' @@ -26,6 +25,7 @@ require_relative 'oga/xml/xml_declaration' require_relative 'oga/xml/doctype' require_relative 'oga/xml/attribute' require_relative 'oga/xml/namespace' +require_relative 'oga/xml/element' require_relative 'oga/xml/node_set' require_relative 'oga/html/parser' diff --git a/lib/oga/xml/element.rb b/lib/oga/xml/element.rb index bb44677..5c2643d 100644 --- a/lib/oga/xml/element.rb +++ b/lib/oga/xml/element.rb @@ -19,6 +19,17 @@ module Oga class Element < Node attr_accessor :name, :namespace, :attributes + ## + # List of options that can be passed to the constructor and the required + # types of their values. + # + # @return [Hash] + # + OPTION_TYPES = { + :namespace => Namespace, + :attributes => Array + } + ## # @param [Hash] options # @@ -31,12 +42,7 @@ module Oga # of the element as an Array. # def initialize(options = {}) - if options[:namespace] and !options[:namespace].is_a?(Namespace) - raise( - TypeError, - ':namespace must be an instance of Oga::XML::Namespace' - ) - end + validate_option_types!(options) super @@ -141,6 +147,21 @@ module Oga private + ## + # @param [Hash] options + # @raise [TypeError] + # + def validate_option_types!(options) + OPTION_TYPES.each do |key, type| + if options[key] and !options[key].is_a?(type) + raise( + TypeError, + "#{key.inspect} must be an instance of #{type}" + ) + end + end + end + ## # @param [String] name # @return [Array] diff --git a/spec/oga/xml/element_spec.rb b/spec/oga/xml/element_spec.rb index 7e7ddf6..f1eebba 100644 --- a/spec/oga/xml/element_spec.rb +++ b/spec/oga/xml/element_spec.rb @@ -6,12 +6,18 @@ describe Oga::XML::Element do described_class.new(:name => 'p').name.should == 'p' end - example 'raise TypeError when the namespace is a String' do + example 'raise TypeError when the namespace is not a Namespace' do block = lambda { described_class.new(:namespace => 'x') } block.should raise_error(TypeError) end + example 'raise TypeError when the attributes are not an Array' do + block = lambda { described_class.new(:attributes => 'foo') } + + block.should raise_error(TypeError) + end + example 'set the name via a setter' do instance = described_class.new instance.name = 'p'