Skip to content

Commit

Permalink
Render all primitive types natively
Browse files Browse the repository at this point in the history
If passed a String, Number, Boolean or Null value, `#serializer_for`
should understand that the value doesn't need a custom serializer with
all the bells and whistles.
  • Loading branch information
foca committed Mar 14, 2015
1 parent 562d85c commit 7e0286e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
11 changes: 8 additions & 3 deletions lib/granola/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,19 @@ def self.serializer_class_for(object)
name = object.class.name
Object.const_get("%sSerializer" % name)
rescue NameError
const_get("%sSerializer" % name)
case object
when NilClass, TrueClass, FalseClass, Numeric, String
PrimitiveTypesSerializer
else
raise
end
end

# Internal: Null serializer that transparently handles rendering `nil` in case
# it's passed.
class NilClassSerializer < Granola::Serializer
class PrimitiveTypesSerializer < Granola::Serializer
def serialized
{}
object
end
end
end
12 changes: 10 additions & 2 deletions test/helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class ModelSerializer < Granola::Serializer
assert_equal PersonSerializer, klass

klass = Granola::Helper.serializer_class_for([])
assert_equal Granola::Helper::NilClassSerializer, klass
assert_equal Granola::Helper::PrimitiveTypesSerializer, klass

klass = Granola::Helper.serializer_class_for(Namespaced::Model.new)
assert_equal Namespaced::ModelSerializer, klass
Expand All @@ -53,7 +53,8 @@ class ModelSerializer < Granola::Serializer
test "#serializer_for handles empty lists automatically" do
serializer = serializer_for([])
assert serializer.is_a?(Granola::List)
assert_equal Granola::Helper::NilClassSerializer, serializer.item_serializer
assert_equal \
Granola::Helper::PrimitiveTypesSerializer, serializer.item_serializer
end

test "#serializer_for accepts a Granola::Serializer" do |person|
Expand All @@ -67,3 +68,10 @@ class ModelSerializer < Granola::Serializer
assert_equal expected, actual
assert PersonSerializer === actual
end

test "#serializer_for correctly serializes primitive types" do
[nil, true, false, 10, 5.0, "foo"].each do |primitive_type|
serializer = serializer_for(primitive_type)
assert_equal primitive_type, serializer.serialized
end
end

0 comments on commit 7e0286e

Please sign in to comment.