From b32a03352fa7d11ce50fc5481647314c6d408d7f Mon Sep 17 00:00:00 2001 From: Campbell Allen Date: Wed, 10 Dec 2014 06:28:27 +1000 Subject: [PATCH] raise explicit error when unknown serializer avoid use of runtime error to distinguish this event from other run time error classes. --- lib/restpack_serializer/factory.rb | 30 ++++++++++++++++++------------ spec/factory/factory_spec.rb | 12 ++++++++++++ 2 files changed, 30 insertions(+), 12 deletions(-) diff --git a/lib/restpack_serializer/factory.rb b/lib/restpack_serializer/factory.rb index dd8d0cf..fc73d8c 100644 --- a/lib/restpack_serializer/factory.rb +++ b/lib/restpack_serializer/factory.rb @@ -1,18 +1,24 @@ -class RestPack::Serializer::Factory - def self.create(*identifiers) - serializers = identifiers.map { |identifier| self.classify(identifier) } - serializers.count == 1 ? serializers.first : serializers - end +module RestPack::Serializer + + class UnknownSerializer < StandardError; end - private + class Factory - def self.classify(identifier) - normalised_identifier = identifier.to_s.underscore - [normalised_identifier, normalised_identifier.singularize].each do |format| - klass = RestPack::Serializer.class_map[format] - return klass.new if klass + def self.create(*identifiers) + serializers = identifiers.map { |identifier| self.classify(identifier) } + serializers.count == 1 ? serializers.first : serializers end - raise "Invalid RestPack::Serializer : #{identifier}" + private + + def self.classify(identifier) + normalised_identifier = identifier.to_s.underscore + [normalised_identifier, normalised_identifier.singularize].each do |format| + klass = RestPack::Serializer.class_map[format] + return klass.new if klass + end + + raise UnknownSerializer.new("Unknown serializer class: #{identifier}") + end end end diff --git a/spec/factory/factory_spec.rb b/spec/factory/factory_spec.rb index c481200..2974bab 100644 --- a/spec/factory/factory_spec.rb +++ b/spec/factory/factory_spec.rb @@ -32,6 +32,7 @@ it "creates multi-word string" do factory.create("AlbumReview").should be_an_instance_of(MyApp::AlbumReviewSerializer) end + it "creates multi-word lowercase string" do factory.create("album_review").should be_an_instance_of(MyApp::AlbumReviewSerializer) end @@ -46,4 +47,15 @@ end end + describe "unknown serializer word" do + + it "raises a custom exception" do + unknown_serializer_class = "UnknownModelType" + message = "Unknown serializer class: #{unknown_serializer_class}" + expect do + factory.create(unknown_serializer_class).should + end.to raise_error(RestPack::Serializer::UnknownSerializer, message) + end + end + end