1
0
Fork 0
mirror of https://github.com/thoughtbot/factory_bot.git synced 2022-11-09 11:43:51 -05:00

Only undefine methods that were previously defined

In 241e8e5fb4, this call to `undef_method`
was introduced to suppress the warning printed by Ruby when a method is
redefined.

That warning is only printed when the method is already defined on the
class in question; it isn't printed when the method was inherited from
an ancestor, since overriding methods by shadowing them is a feature.

However, `method_defined?` returns true for inherited methods, which
means we're sometimes undefining methods that wouldn't cause a warning.

If a factory defines an attribute named `object_id` (admittedly not a
great idea), we will undefine the `object_id` method inherited from the
`Object` class, and the following warning will be printed:

    factory_bot/evaluator.rb:70: warning: undefining `object_id' may cause serious problems

By only undefining the method if it's defined on the current class, we
can avoid undefining inherited methods and triggering this warning.
This commit is contained in:
Eugene Kenny 2019-03-20 23:24:37 +00:00 committed by Daniel Colson
parent 69d930babd
commit e7ddcbccc5

View file

@ -66,7 +66,7 @@ module FactoryBot
end
def self.define_attribute(name, &block)
if method_defined?(name) || private_method_defined?(name)
if instance_methods(false).include?(name) || private_instance_methods(false).include?(name)
undef_method(name)
end