From b9d56a5168dd83ee464109d24c4ff002e08415eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Valim?= Date: Wed, 21 Dec 2011 09:11:04 +0100 Subject: [PATCH] Fix constant lookup when serializer is not available. --- lib/active_model_serializers.rb | 21 +++++++++++++-------- test/serializer_support_test.rb | 11 +++++++++++ 2 files changed, 24 insertions(+), 8 deletions(-) create mode 100644 test/serializer_support_test.rb diff --git a/lib/active_model_serializers.rb b/lib/active_model_serializers.rb index 3019cd99f..b6248b375 100644 --- a/lib/active_model_serializers.rb +++ b/lib/active_model_serializers.rb @@ -5,14 +5,19 @@ module ActiveModel::SerializerSupport extend ActiveSupport::Concern module ClassMethods #:nodoc: - def active_model_serializer - return @active_model_serializer if defined?(@active_model_serializer) - - # Use safe constantize when Rails 3.2 is out - begin - @active_model_serializer = "#{self.name}Serializer".constantize - rescue NameError => e - raise unless e.message =~ /uninitialized constant$/ && e.name.to_s == "#{self.name}Serializer" + if "".respond_to?(:safe_constantize) + def active_model_serializer + @active_model_serializer ||= "#{self.name}Serializer".safe_constantize + end + else + def active_model_serializer + return @active_model_serializer if defined?(@active_model_serializer) + + begin + @active_model_serializer = "#{self.name}Serializer".constantize + rescue NameError => e + raise unless e.message =~ /uninitialized constant/ + end end end end diff --git a/test/serializer_support_test.rb b/test/serializer_support_test.rb new file mode 100644 index 000000000..b2d2b8be4 --- /dev/null +++ b/test/serializer_support_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class RandomModel + include ActiveModel::SerializerSupport +end + +class SerializerSupportTest < ActiveModel::TestCase + test "it returns nil if no serializer exists" do + assert_equal nil, RandomModel.new.active_model_serializer + end +end \ No newline at end of file