Skip to content

Commit 3f16b75

Browse files
author
Lee Richmond
committed
Ensure generator picks up ApplicationSerializer
ApplicationSerializer could exist, but not be loaded. So, we check existence by looking at the filesystem instead of defined?. Fixes #1890
1 parent 1dc2b74 commit 3f16b75

File tree

3 files changed

+24
-6
lines changed

3 files changed

+24
-6
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ Breaking changes:
77
Fixes:
88

99
- [#1887](https://github.com/rails-api/active_model_serializers/pull/1887) Make the comment reflect what the function does (@johnnymo87)
10+
- [#1890](https://github.com/rails-api/active_model_serializers/issues/1890) Ensure generator inherits from ApplicationSerializer when available (@richmolj)
1011

1112
Features:
1213

lib/generators/rails/serializer_generator.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def association_names
2525
def parent_class_name
2626
if options[:parent]
2727
options[:parent]
28-
elsif defined?(::ApplicationSerializer)
28+
elsif 'ApplicationSerializer'.safe_constantize
2929
'ApplicationSerializer'
3030
else
3131
'ActiveModel::Serializer'

test/generators/serializer_generator_test.rb

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,10 @@ def test_generates_a_namespaced_serializer
2020
end
2121

2222
def test_uses_application_serializer_if_one_exists
23-
Object.const_set(:ApplicationSerializer, Class.new)
24-
run_generator
25-
assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/
26-
ensure
27-
Object.send :remove_const, :ApplicationSerializer
23+
stub_safe_constantize(expected: 'ApplicationSerializer') do
24+
run_generator
25+
assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/
26+
end
2827
end
2928

3029
def test_uses_given_parent
@@ -54,4 +53,22 @@ def test_with_no_attributes_does_not_add_extra_space
5453
end
5554
end
5655
end
56+
57+
private
58+
59+
def stub_safe_constantize(expected:)
60+
String.class_eval do
61+
alias_method :old, :safe_constantize
62+
end
63+
String.send(:define_method, :safe_constantize) do
64+
Class if self == expected
65+
end
66+
67+
yield
68+
ensure
69+
String.class_eval do
70+
alias_method :safe_constantize, :old
71+
undef_method :old
72+
end
73+
end
5774
end

0 commit comments

Comments
 (0)