Rails: Do not load frameworks you don't need

Updated . Posted . Visible to the public. Repeats.

Rails is split into a large number of (sub-) frameworks.

The most important and central of those are

  • activesupport (extends the Ruby standard library)
  • activerecord / activemodel (ORM for Rails)
  • actionview / actionpack (controller / views)
  • actionmailer (sends mails)

However, there are also some more situational frameworks included, such as

  • actioncable (real time communications using websockets)
  • actionmailbox (receives mails)
  • actiontext (support for WYSIWYG text editor)
  • activejob (background jobs)
  • activestorage (file upload and storage)
  • sprockets (the old "asset pipeline")

You might not need all of these frameworks in every app, so in the interest of startup time and memory usage, you can disable them. To do that, simply comment out the appropriate lines in config/application.rb. You'll also have to remove some configuration options, but you'll receive appropriate error messages.

Practical Steps

  • If your application.rb only has require 'rails/all', you need to replace that line with individual requires for the frameworks you would like to keep.

  • Since every gem from your gemfile is loaded, set require: false in your gemfile for any not needed sub-framework (e.g. gem 'actionmailer', require: false) as well.

  • When you look into the definition of rails/all (in railites-x.x.x/lib-/rails/all.rb) you can find the exact path for requiring the sub-frameworks.

    • You can only copy those paths which you actually needed for your application.
  • If your application now fails on start up, make sure that no configs are set for the now un-required frameworks. Some settings can be set by the default rails app generator.

Example

%w(
  active_record/railtie
  action_controller/railtie
  action_view/railtie
  action_mailer/railtie
  action_mailbox/engine
).each do |railtie|
  require railtie
end
Tobias Kraze
Last edit
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Tobias Kraze to makandra dev (2019-08-26 11:40)