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

MONGOID-5816: attr_readonly leaks into sibling classes (backport for 9.0) #5919

Merged
Merged
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
11 changes: 8 additions & 3 deletions lib/mongoid/attributes/readonly.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ module Readonly
# @return [ true | false ] If the document is new, or if the field is not
# readonly.
def attribute_writable?(name)
new_record? || (!readonly_attributes.include?(name) && _loaded?(name))
new_record? || (!self.class.readonly_attributes.include?(name) && _loaded?(name))
end

private
Expand Down Expand Up @@ -63,12 +63,17 @@ module ClassMethods
# end
#
# @param [ Symbol... ] *names The names of the fields.
# @note When a parent class contains readonly attributes and is then
# inherited by a child class, the child class will inherit the
# parent's readonly attributes at the time of its creation.
# Updating the parent does not propagate down to child classes after wards.
def attr_readonly(*names)
self.readonly_attributes = self.readonly_attributes.dup
names.each do |name|
readonly_attributes << database_field_name(name)
self.readonly_attributes << database_field_name(name)
end
end
end
end
end
end
end
19 changes: 19 additions & 0 deletions spec/mongoid/attributes/readonly_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,26 @@
expect(child.mother).to be_nil
end
end
end

context "when a subclass inherits readonly fields" do
let(:attributes) do
[:title, :terms]
end

before do
class OldPerson < Person
attr_readonly :age
end
end

it "ensures subclass inherits the readonly attributes from parent" do
expect(OldPerson.readonly_attributes.to_a).to include("title","terms")
end

it "ensures subclass does not modify parent's readonly attributes" do
expect(Person.readonly_attributes.to_a).not_to include("age")
end
end
end
end
Loading