Roger Roger - 6 months ago 20
Ruby Question

Rails same file name for different classes

Having model Price (models/price.rb)

class Price
end


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

class Import::Detector::Price
end


Lib directory added to autoload paths via

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


So running Price.new I get error

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

Import::Detector::Price.new is ok

What was my mistake?

UPD.
The most interesting

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

class Car::Property::Price
end


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

Rob Rob
Answer

Try

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