From f8b637e47948bb67fcf7fc5091e6d3d8c3e1e009 Mon Sep 17 00:00:00 2001 From: Lee Richmond Date: Mon, 5 Sep 2016 09:48:06 -0400 Subject: [PATCH] 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 https://github.com/rails-api/active_model_serializers/issues/1890 --- CHANGELOG.md | 1 + lib/generators/rails/serializer_generator.rb | 2 +- test/generators/serializer_generator_test.rb | 26 ++++++++++++++++---- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 417197494..c00f90e29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Breaking changes: Fixes: - [#1887](https://github.com/rails-api/active_model_serializers/pull/1887) Make the comment reflect what the function does (@johnnymo87) +- [#1890](https://github.com/rails-api/active_model_serializers/issues/1890) Ensure generator Inherits from ApplicationSerializer when available (@richmolj) Features: diff --git a/lib/generators/rails/serializer_generator.rb b/lib/generators/rails/serializer_generator.rb index 16a47a61c..e670d5cf6 100644 --- a/lib/generators/rails/serializer_generator.rb +++ b/lib/generators/rails/serializer_generator.rb @@ -25,7 +25,7 @@ def association_names def parent_class_name if options[:parent] options[:parent] - elsif defined?(::ApplicationSerializer) + elsif 'ApplicationSerializer'.safe_constantize 'ApplicationSerializer' else 'ActiveModel::Serializer' diff --git a/test/generators/serializer_generator_test.rb b/test/generators/serializer_generator_test.rb index 562b93380..54a678b16 100644 --- a/test/generators/serializer_generator_test.rb +++ b/test/generators/serializer_generator_test.rb @@ -20,11 +20,10 @@ def test_generates_a_namespaced_serializer end def test_uses_application_serializer_if_one_exists - Object.const_set(:ApplicationSerializer, Class.new) - run_generator - assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/ - ensure - Object.send :remove_const, :ApplicationSerializer + stub_safe_constantize(expected: 'ApplicationSerializer') do + run_generator + assert_file 'app/serializers/account_serializer.rb', /class AccountSerializer < ApplicationSerializer/ + end end def test_uses_given_parent @@ -54,4 +53,21 @@ def test_with_no_attributes_does_not_add_extra_space end end end + + private + + def stub_safe_constantize(expected:) + String.class_eval do + alias_method :old, :safe_constantize + end + String.send(:define_method, :safe_constantize) do + Class if self == expected + end + + yield + ensure + String.class_eval do + alias_method :safe_constantize, :old + end + end end