Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Test for symbolizing :root key #317

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib/active_model/serializer/associations.rb
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ def initialize(name, options={}, serializer_options={})

def root
if root = options[:root]
root
root.to_sym
elsif polymorphic?
object.class.to_s.pluralize.demodulize.underscore.to_sym
else
Expand Down
41 changes: 41 additions & 0 deletions test/serializer_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1518,4 +1518,45 @@ def test_only_option_takes_precedence_over_custom_defined_include_methods
}
}, post_serializer.as_json)
end

def test_root_key_can_be_string
company_serializer = Class.new(ActiveModel::Serializer) do
root :companies

embed :ids, :include => true

has_many :contacts
has_one :primary_contact, :root => 'contacts'
end

contact_serializer = Class.new(ActiveModel::Serializer) do
root :contacts

attributes :id, :name
end

company_klass = Struct.new(:contacts, :primary_contact) do
define_method :active_model_serializer do
company_serializer
end
end

contact_klass = Struct.new(:id, :name) do
define_method :active_model_serializer do
contact_serializer
end
end

contacts = [contact_klass.new(1, 'Adam'), contact_klass.new(2, 'Paul')]
primary_contact = contact_klass.new(3, 'Sami')

company = company_klass.new contacts, primary_contact
serializer = company_serializer.new company

hash = serializer.as_json

refute hash.key?('contacts'), "Key should be used as a symbol"
assert hash.key?(:contacts), "Key should be used as a symbol"
assert_equal 3, hash[:contacts].size
end
end