"Module.const_defined?" behaves differently in Ruby 1.9 and Ruby 1.8

Posted . Visible to the public.

Ruby 1.9 changed the default behavior of Module.const_defined? from what it was in Ruby 1.8 -- this can be especially painful when external code (read: gems) uses const_defined? to look something up and gets different results on different Rubies.

Consider this:

module Foo
  FOO = 42
end

class Bar
  include Foo
end

On Ruby 1.8 Show archive.org snapshot , Bar won't have FOO defined as a constant since that's (even though it's accessible):

1.8.7 > Foo.const_defined? :FOO
 => true 
1.8.7 > Bar.const_defined? :FOO
 => false 
1.8.7 > Bar::FOO
 => 42 

Ruby 1.9 Show archive.org snapshot introduces a switch (defaulting to true) that also looks at the ancestor classes/modules. This leads to different results:

1.9.3 > Foo.const_defined? :FOO
 => true 
1.9.3 > Bar.const_defined? :FOO
 => true 
1.9.3 > Bar::FOO
 => 42 

To get the old behavior back, you need to pass false as a second option:

1.9.3 > Bar.const_defined? :FOO, false
 => false 
Arne Hartherz
Last edit
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2013-03-01 12:27)