I'm trying to create a custom exceptions for my app. I have a sample library in my libs folder with the following folder structure:
- lib/
|
|--social/
|
|-- bandcamp.rb
And this bandcamp.rb
file contents looks following:
module Social
class ExampleException < Exception; end
class Bandcamp
def some_method()
end
end
end
And the thing is, i can use a Social::Bandcamp.new.some_method
anywhere in my app and it works just fine but i can't access Social::ExampleException
nor raise it anywhere. It gives me
NameError: uninitialized constant Social::ExampleException
Have you any idea what am i possibly doing wrong? I'm quite new to creating own libs so i'm sure i've misunderstood something.
The problem here is that lib/
files are autoloaded (config.autoload_paths
).
Autoload depends on filenames in order to find needed class.
The file named bandcamp.rb
will be loaded only when you call Social::Bandcamp
and only then you'll be able to access other classes defined there.
The solution is to create separate files for exceptions or turn on eager loading of this directory.
You are probably being bitten by Rails classes' eager loading. Why? See:
2.0.0p353 :001 > Social.constants
=> []
2.0.0p353 :002 > raise Social::ExampleException
NameError: uninitialized constant Social::ExampleException
2.0.0p353 :003 > Social::Bandcamp
=> Social::Bandcamp
2.0.0p353 :004 > Social.constants
=> [:ExampleException, :Bandcamp]
2.0.0p353 :005 > raise Social::ExampleException
Social::ExampleException: Social::ExampleException
TIf you want to change that behaviour you should turn on eager loading of lib
directory (by default only app
is loaded), to do this add to your environment.rb
(or specific environment setting):
config.eager_load_paths += %W(#{config.root}/lib)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With