rcrogers
rcrogers

Reputation: 2331

Inconsistent behavior when referencing constants inside a module

In my Rails 3.2 models directory, I have a folder "foo" containing two classes:

# foo/bar.rb
class Foo::Bar; end

# foo/baz.rb
class Foo::Baz
  def self.test
    puts Bar.to_s
  end
end

Note that Foo::Baz.test references Foo::Bar as simply Bar, since Bar and Baz are in the same module.

I then open the console and call Foo::Baz.test twice:

1.9.3-p0 :001 > Foo::Baz.test
Foo::Bar
 => nil 
1.9.3-p0 :002 > Foo::Baz.test
NameError: uninitialized constant Foo::Baz::Bar
    from /../app/models/foo/baz.rb:2:in `test'

As you can see, the call works fine the first time, and then crashes every time thereafter. Why?

This does not happen if Foo::Baz uses the fully qualified name Foo::Bar instead of just Bar.

Upvotes: 3

Views: 108

Answers (1)

Wayne Conrad
Wayne Conrad

Reputation: 107999

It appears to work if you declare the module separately:

# foo/bar.rb
module Foo
  class Bar; end
end

# foo/baz.rb
module Foo
  class Baz
    def self.test
      puts Bar.to_s
    end
  end
end

$ rails console
Loading development environment (Rails 3.2.6)
1.9.3-p125 :001 > Foo::Baz.test
Foo::Bar
 => nil 
1.9.3-p125 :002 > Foo::Baz.test
Foo::Bar
 => nil 
1.9.3-p125 :003 > 

I cannot explain why.

Upvotes: 2

Related Questions