Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - :: in class name

I'm working with some legacy RoR code, which has four related classes, each defined in its own file. All of these classes are parser classes, and live in app/models/parsers. Each file name ends with _parser.rb.

Here's an example class def line from file adf_parser.rb:

class Parsers::AdfParser

I'm lost as to what the Parsers:: part of that is doing.

  • There's no explicit module called Parsers defined anywhere that I can find.
  • I don't see any documentation about implicitly creating modules just by adding module specifications to class names.
  • The only external dependency is "require 'csv'".
  • There are include statements within the class def, but I don't think they have anything that would explain the class name.
  • I created a new RoR test project and put stubs of these files in a parallel directory, and they won't run from the command line due to a name error.
  • I don't see any examples online of classes named in this way.

I'm sure this isn't rocket surgery, but I've lost most of my morning trying to figure this out, and I'd love it if someone could just tell me what's going on with it.

Update: It sounds like this is just a bit of Rails magic, based on the subdirectory name. I think the reason that I got an error in my test app is that I just ran the files through the ruby interpreter, rather than invoking them with Rails in some way.

like image 938
whognu Avatar asked Mar 19 '13 17:03

whognu


2 Answers

class Parsers::AdfParser is in practice equivalent to:

module Parsers
  class AdfParser

For this to work properly, and the file to be autoloaded its location should be parsers/adf_parser.rb, whether under app/models or lib. Basically the file path needs to mimic the class hierarchy.

like image 59
boulder Avatar answered Oct 30 '22 09:10

boulder


It's in the parsers sub-directory of modules; Rails namespaces for you by convention.

like image 3
Dave Newton Avatar answered Oct 30 '22 09:10

Dave Newton