Skip to content

Commit

Permalink
Fix constant lookup when serializer is not available.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed Dec 21, 2011
1 parent cc5f102 commit b9d56a5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
21 changes: 13 additions & 8 deletions lib/active_model_serializers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions test/serializer_support_test.rb
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit b9d56a5

Please sign in to comment.