Read more

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

Arne Hartherz
March 01, 2013Software engineer at makandra GmbH

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.

Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

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 
Posted by Arne Hartherz to makandra dev (2013-03-01 13:27)