Skip to content

Commit

Permalink
MONGOID-4737 Deprecate the :compact option on Document#as_json (#5040)
Browse files Browse the repository at this point in the history
* MONGOID-4737 Deprecate the :compact option on Document#as_json

* Update document_spec.rb

* Explicitly specify warning to not receive

Co-authored-by: shields <[email protected]>
  • Loading branch information
johnnyshields and johnnyshields authored Aug 23, 2021
1 parent af797ed commit eaa6d26
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
5 changes: 3 additions & 2 deletions lib/mongoid/document.rb
Original file line number Diff line number Diff line change
Expand Up @@ -173,13 +173,14 @@ def as_document
#
# @param [ Hash ] options The options.
#
# @option options [ true, false ] :compact Whether to include fields with
# nil values in the json document.
# @option options [ true, false ] :compact (Deprecated) Whether to include fields
# with nil values in the json document.
#
# @return [ Hash ] The document as json.
def as_json(options = nil)
rv = super
if options && options[:compact]
Mongoid.logger.warn('#as_json :compact option is deprecated. Please call #compact on the returned Hash object instead.')
rv = rv.compact
end
rv
Expand Down
2 changes: 1 addition & 1 deletion lib/mongoid/tasks/database.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def shard_collections(models = ::Mongoid.models)
next if model.shard_config.nil?

if model.embedded? && !model.cyclic?
logger.warn("MONGOID: #{model} has shard config but is emdedded")
logger.warn("MONGOID: #{model} has shard config but is embedded")
next
end

Expand Down
22 changes: 21 additions & 1 deletion spec/mongoid/document_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ class << self; attr_accessor :name; end
end
end

context ':compact option' do
context 'deprecated :compact option' do
# Since rails 6 differs in how it treats id fields,
# run this test on one version of rails. Currently rails 6 is in beta,
# when it is released this version should be changed to 6.
Expand All @@ -512,6 +512,26 @@ class << self; attr_accessor :name; end
expect(church.as_json.keys.sort).to eq(%w(_id location name))
end

context 'deprecation' do
let(:church) do
Church.create!(name: 'St. Basil')
end

let(:message) do
'#as_json :compact option is deprecated. Please call #compact on the returned Hash object instead.'
end

it 'logs a deprecation warning when :compact is given' do
expect_any_instance_of(Logger).to receive(:warn).with(message)
church.as_json(compact: true)
end

it 'does not log a deprecation warning when :compact is not given' do
expect_any_instance_of(Logger).to_not receive(:warn).with(message)
church.as_json
end
end

context 'there is a nil valued attribute' do
let(:church) do
Church.create!(name: 'St. Basil')
Expand Down

0 comments on commit eaa6d26

Please sign in to comment.