Class name and NameError: uninitialized constant

Hi All:

I'm just getting started with rails and have run into a problem with class names. If I create a class, and call it MyClass, it throws the following error.

@my_class = MyClass.new

NameError: uninitialized constant MyClass   from /Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/ active_support/dependencies.rb:266:in `load_missing_constant'   from /Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/ active_support/dependencies.rb:453:in `const_missing'   from /Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/ active_support/dependencies.rb:465:in `const_missing'   from (irb):47

However, if I rename it Myclass (note the capitalisation), it works:

@my_class = Myclass.new

=> #<Myclass:0x1224470>

Is it supposed to work like this? I am using Rails 2.0.2 on Mac OS X Leopard 10.5.2

Thanks ... Rich

(Simplifying slightly) When rails hits a const_missing, it will underscorize the class name and try and load that file. So when it hits MyClass it will look for my_class.rb and if it hits Myclass it will look for myclass.rb. Either is fine, but don't mix and match: it sounds like you've got MyClass in a file named my_class

Fred

Hi Fred.

That's interesting. The MyClass file was called MyClass.rb. I've just tried naming the file to My_Class.rb (with the class still called MyClass) , and then it works. Therefore I guess I should underscorize any capitalized class files? :slight_smile:

Thanks very much!

Cheers ... Rich

Rich wrote:

Hi Fred.

That's interesting. The MyClass file was called MyClass.rb. I've just tried naming the file to My_Class.rb (with the class still called MyClass) , and then it works. Therefore I guess I should underscorize any capitalized class files? :slight_smile:

You should generally name everything _exactly_ following the patterns you will find in 'script/generate model', in the various Rails books, in the scaffold generators, and in the blogosphere. script/generate model my_class will create my_class.rb, containing class MyClass. Your tweak, My_Class.rb, might not work on case-sensitive filesystems. (But then it might work anyway, because I thought Leopard was a Un*x in a fuzzy spotted coat).

Rails is opinionated, and works best when it can configure by convention. (Compare the agony of systems that configure via endless ANT and property files...) But that's not the only reason to follow all these conventions.

All projects should have a consistent coding style. The best source for this is your main library. So when in Rome, do as the Romans do!

Hi Phlip:

I'll do just that, and name them my_class.rp. Must have missed it somewhere in the book I'm reading or just not got that far yet.

Thanks ... Rich

P.S. It's breath of fresh air having come from c# and all the ms stuff. Even the books don't send you to sleep.