Skip to content

Commit

Permalink
Ensure generator picks up ApplicationSerializer
Browse files Browse the repository at this point in the history
ApplicationSerializer could exist, but not be loaded. So, we check
existence by looking at the filesystem instead of defined?.

Fixes rails-api#1890
  • Loading branch information
Lee Richmond committed Sep 5, 2016
1 parent 1dc2b74 commit f8b637e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
2 changes: 1 addition & 1 deletion lib/generators/rails/serializer_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
26 changes: 21 additions & 5 deletions test/generators/serializer_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

0 comments on commit f8b637e

Please sign in to comment.