Read more

Rails: Do not load frameworks you don't need

Tobias Kraze
August 26, 2019Software engineer at makandra GmbH

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

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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
Posted by Tobias Kraze to makandra dev (2019-08-26 13:40)