Roger Roger - 2 years ago 88
Ruby Question

Rails same file name for different classes

Having model Price (models/price.rb)

class Price

Also in lib directory I have import/detector/price.rb file

class Import::Detector::Price

Lib directory added to autoload paths via

config.autoload_paths += Dir["#{config.root}/lib/**/"]

So running I get error

Unable to autoload constant Price, expected lib/import/detector/price.rb to define it. is ok

What was my mistake?

The most interesting

Also having this file models/car/property/price.rb

class Car::Property::Price

And everything ok with it. Car::Property::Price is available.

Rob Rob
Answer Source


config.autoload_paths += Dir["#{config.root}/lib"]

instead of

config.autoload_paths += Dir["#{config.root}/lib/**/"]

Using **, Dir will return every directory under lib and will put them all (as root directories) in the load path. It should only be the main lib directory in the load path as rails will work out the subdirectories using the namespace.

Rails autoloading — how it works, and when it doesn't

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download