Rails 3 library not loading until require

后端 未结 2 1110
攒了一身酷
攒了一身酷 2020-11-30 02:22

I\'m trying to load the Tokbox SDK in rails 3. I\'ve placed the library in my /lib directory, so currently my directory structure looks like so:

/lib
 &nb

相关标签:
2条回答
  • 2020-11-30 02:31

    Auto-loading works fine as long as the class in your file is a class that is only defined in that file. It doesn't work if you're wanting to re-open an existing class (originally defined in standard Ruby, Rails, or another library) and customize it in some way.

    Example of problem:

    Here's an example of a file in lib/ that would never get autoloaded:

    lib/active_record/base_extensions.rb:

    ActiveRecord::Base   # make sure ActiveRecord::Base is loaded
    module ActiveRecord::Base::Extensions
      # some methods here
    end
    
    class ActiveRecord::Base
      include ActiveRecord::Base::Extensions
    end
    

    This file reopens ActiveRecord::Base and adds some methods to that class.

    What would trigger this file to get autoloaded?? Nothing! Auto-loading is based on constants, and the constant ActiveRecord::Base has already been loaded (from the activerecord gem).

    So referencing the constant ActiveRecord::Base in your app would not cause this particular file to be auto-loaded.

    Workaround:

    This is what I do to ensure that all my Ruby files under lib/ get required:

    Add a new initializer named config/initializers/require_files_in_lib.rb with this contents:

    Dir[Rails.root + 'lib/**/*.rb'].each do |file|
      require file
    end
    
    0 讨论(0)
  • 2020-11-30 02:33

    The autoloader will snake case the constant, so "OpenTok" would make the autoloader look for "open_tok.rb", not "opentok.rb". Try renaming lib/opentok.rb and it should work fine.

    0 讨论(0)
提交回复
热议问题