Skip to content

Commit

Permalink
raise explicit error when unknown serializer
Browse files Browse the repository at this point in the history
avoid use of runtime error to distinguish this event from other run time error classes.
  • Loading branch information
camallen committed Dec 9, 2014
1 parent 404bd61 commit b32a033
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
30 changes: 18 additions & 12 deletions lib/restpack_serializer/factory.rb
Original file line number Diff line number Diff line change
@@ -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
12 changes: 12 additions & 0 deletions spec/factory/factory_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

0 comments on commit b32a033

Please sign in to comment.