Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unitialized constant when using custom exceptions

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.

like image 936
mbajur Avatar asked Dec 25 '13 23:12

mbajur


2 Answers

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.

like image 93
Bart Avatar answered Nov 08 '22 18:11

Bart


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)
like image 20
zrl3dx Avatar answered Nov 08 '22 18:11

zrl3dx