Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 4 - require class in initializer or module that uses it - best practice

I'm a fairly new RoR dev and ran into a question about best practices for require ing files from lib in Rails 4.

Background:

As it stands, files in my app's lib don't get autoloaded. I want to require a helper class called rate_limiter that lives in a subdirectory of lib. I've also created a throttle module that handles routes related to rate limiting, and uses this rate_limiter class.

The throttle module is already required at the top of my application controller.

Question: to make sure rate_limiter gets loaded at start of app, what's better:

1) include an initializer rate_limiter.rb that simply says require rate_limiter to load class.

2) add require rate_limiter to the top of a different module throttle, which uses rate_limiter and which already gets required at the top of application controller.

Wondering about best practices for clarity and maintainability going forward.

Thanks for any suggestions!

like image 744
abaldwinhunter Avatar asked Jun 07 '15 18:06

abaldwinhunter


2 Answers

I believe this would be a more Rails way to include desired files and folders.

# config/application.rb
module YourAppName
  class Application < Rails::Application
    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)
    config.autoload_paths += Dir[Rails.root.join('lib')]
  end
end
like image 59
twonegatives Avatar answered Oct 12 '22 23:10

twonegatives


You probably could try the following scheme:

# config/application.rb:

# To make sure that your module namespace will be initialized without name collisions with files in your app directories
# require only root file and autoload other relative files in root file using features of ActiveSupport::Autoload
require_relative '../lib/my_module/my_module'

module AppName
  class Application < Rails::Application
    # Do not include all files in your lib. Require explicitly
    # .
    # ..
    # - lib/my_module/my_module.rb - root file
    # - lib/my_module/my_module - directory
    config.autoload_paths += Dir[Rails.root.join('lib', 'my_module')]
  end
end

Then in you module you can specify explicitly which files required and when

# lib/my_module/my_module.rb 
module MyModule
  extend ActiveSupport::Autoload

  autoload :Configuration
  autoload :SomeClass # at lib/my_module/my_module/some_class.rb
  autoload :AnotherClass

  eager_autoload do
    autoload :Errors # at lib/my_module/my_module/errors.rb
    autoload :BillError, 'my_module/errors'
  end
end

It is worth to read an official guide to understand generic process of Rails constant lookup

like image 34
Mihail Davydenkov Avatar answered Oct 13 '22 01:10

Mihail Davydenkov