Skip to content

Instantly share code, notes, and snippets.

@bohford
Created September 10, 2010 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bohford/574051 to your computer and use it in GitHub Desktop.
Save bohford/574051 to your computer and use it in GitHub Desktop.
module AutoloadMissingConstants
# Automatically loads constants that Ruby doesn't know about when unmarshalling in the given block. This triggers
# Rails/ActiveSupport's smart autoloading code via constantize. Adapted from cache_fu/cache_methods.rb:214
#
# ==== Parameters
#
# &block:: Unmarshalling block.
#
# ==== Raises
#
# NameError:: Constant can't be found.
#
def self.protect
yield
rescue ArgumentError => e
raise unless e.to_s =~ /undefined class/ # unexpected error message, re-raise
e.to_s.split.last.constantize # raises NameError if it can't find the constant
retry
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment