Skip to content

Instantly share code, notes, and snippets.

@joakimk
Last active December 25, 2015 03:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joakimk/6914422 to your computer and use it in GitHub Desktop.
Save joakimk/6914422 to your computer and use it in GitHub Desktop.
Using rails constant missing features (ActiveSupport::Dependencies) outside of rails

Using ActiveSupport::Dependencies outside of rails seems just as fast as doing manual requires. I've found this out by replacing hundreds of requires in a unit tested code base with ActiveSupport::Dependencies without any change to the time it takes to run the test suite.

Using ActiveSupport::Dependencies also allows you to have circular depedencies like class Foo::Bar in foo/bar.rb and class Foo in foo.rb that points to Foo::Bar in it's class definition (like in a rails validation).

The classical way of solving this without ActiveSupport::Dependencies is to do:

# foo/bar.rb
class Foo
  class Bar

But this breaks if Foo inherits from something (like ActiveRecord::Base) and you don't specify that in foo/bar.rb too (results in a superclass mismatch error if foo/bar.rb is loaded before foo.rb).

require "active_support/dependencies"
ActiveSupport::Dependencies.autoload_paths += [ "lib", "app/models" ]
# Refering to Foo::Bar in the code now loads "lib/foo/bar.rb" or "app/models/foo/bar.rb"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment