Skip to content

Commit

Permalink
Field definition should remove any existing accessors before setting …
Browse files Browse the repository at this point in the history
…its own ones
  • Loading branch information
cperezabo committed Aug 15, 2024
1 parent 69eaf1d commit 59c01e4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/mongoid/fields.rb
Original file line number Diff line number Diff line change
Expand Up @@ -622,6 +622,7 @@ def process_options(field)
def create_accessors(name, meth, options = {})
field = fields[name]

remove_any_existing_accessors(meth)
create_field_getter(name, meth, field)
create_field_getter_before_type_cast(name, meth)
create_field_setter(name, meth, field)
Expand All @@ -634,6 +635,19 @@ def create_accessors(name, meth, options = {})
end
end

# Remove any existing accessors that collide with field's ones
#
# @example Remove any existing accessors.
# Model.remove_any_existing_accessors("name")
#
# @param [ String ] meth The name of the method.
#
# @api private
def remove_any_existing_accessors(meth)
remove_method(meth) if method_defined?(meth, false)
remove_method("#{meth}=") if method_defined?("#{meth}=", false)
end

# Create the getter method for the provided field.
#
# @example Create the getter.
Expand Down
16 changes: 16 additions & 0 deletions spec/mongoid/fields_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2103,4 +2103,20 @@ class DiscriminatorChild2 < DiscriminatorParent
end
end
end

context "when accessors are already present" do
let(:klass) do
Class.new do
attr_accessor :name
include Mongoid::Document
store_in collection: :any
field :name
end
end

it "they are replaced by the field accessors" do
klass.create! name: "Mongoid"
expect(klass.find_by.name).to eq("Mongoid")
end
end
end

0 comments on commit 59c01e4

Please sign in to comment.