### Setup Loader Source: https://github.com/fxn/zeitwerk/blob/main/README.md Call `setup` on the loader to make it ready to load code. This method is synchronized and idempotent. ```ruby loader.setup ``` -------------------------------- ### Generic Autoloading Setup Source: https://github.com/fxn/zeitwerk/blob/main/README.md Initialize a new Zeitwerk loader and push directories to manage. Call `setup` to activate. ```ruby loader = Zeitwerk::Loader.new loader.push_dir(...) loader.setup # ready! ``` -------------------------------- ### Gem Autoloading Setup Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure Zeitwerk for a gem's main file to enable autoloading. Call `setup` to prepare the loader. ```ruby require 'zeitwerk' loader = Zeitwerk::Loader.for_gem loader.setup # ready! module MyGem # ... end loader.eager_load # optionally ``` -------------------------------- ### Setup Gem Loader with No Warnings Source: https://github.com/fxn/zeitwerk/blob/main/README.md Initialize a Zeitwerk loader for a gem, suppressing warnings for extra files. Call setup to begin loading. ```ruby loader = Zeitwerk::Loader.for_gem(warn_on_extra_files: false) loader.setup ``` -------------------------------- ### Basic Gem Autoloading Setup Source: https://github.com/fxn/zeitwerk/blob/main/README.md This snippet shows the standard setup for a gem using Zeitwerk. It's used in the main file of your gem to enable autoloading. ```ruby require 'zeitwerk' loader = Zeitwerk::Loader.for_gem loader.setup ``` -------------------------------- ### Using the on_setup Callback Source: https://github.com/fxn/zeitwerk/blob/main/README.md Register a callback to be executed when the loader is set up or reloaded. Code within this block is run after Zeitwerk has finished its initial setup. ```ruby loader.on_setup do # Ready to autoload here. end ``` -------------------------------- ### Autoloading Example in MyGem Source: https://github.com/fxn/zeitwerk/blob/main/README.md Demonstrates how Zeitwerk enables autoloading of constants like MyGem::MyLogger without explicit require calls. ```ruby # lib/my_gem.rb (main file) require 'zeitwerk' loader = Zeitwerk::Loader.for_gem loader.setup module MyGem # Since the setup has been performed, at this point we are already able # to reference project constants, in this case MyGem::MyLogger. include MyLogger # (*) end ``` -------------------------------- ### Enable and Perform Code Reloading Source: https://github.com/fxn/zeitwerk/blob/main/README.md Opt-in to code reloading before calling `setup`. Use `reload` to trigger a reload. ```ruby loader = Zeitwerk::Loader.new loader.push_dir(...) loader.enable_reloading # you need to opt-in before setup loader.setup ... loader.reload ``` -------------------------------- ### Push Root Directories Source: https://github.com/fxn/zeitwerk/blob/main/README.md Add root directories from which Zeitwerk should load files using `push_dir`. Customization should be done before calling `setup`. ```ruby loader.push_dir(...) loader.push_dir(...) loader.setup ``` -------------------------------- ### Enable Reloading and Setup Zeitwerk Loader Source: https://github.com/fxn/zeitwerk/blob/main/README.md Enables code reloading for the Zeitwerk loader before setup. This feature is useful during development of running services. ```ruby loader = Zeitwerk::Loader.new loader.push_dir(...) loader.enable_reloading # you need to opt-in before setup loader.setup ``` -------------------------------- ### Reopening Third-Party Namespaces with Zeitwerk Source: https://github.com/fxn/zeitwerk/blob/main/README.md When working with third-party libraries, ensure their namespaces are loaded before calling `loader.setup`. This example shows how to reopen `ActiveJob` and `ActiveJob::QueueAdapters`. ```ruby # lib/active_job/queue_adapters/awesome_queue.rb module ActiveJob module QueueAdapters class AwesomeQueue # ... end end end ``` ```ruby # Ensure these namespaces are reopened, not defined. require 'active_job' require 'active_job/queue_adapters' ``` -------------------------------- ### Gem Extension Autoloading Setup Source: https://github.com/fxn/zeitwerk/blob/main/README.md This is used for gems that extend existing Ruby modules or classes, like Net::HTTP. It requires the namespace being extended as an argument. ```ruby loader = Zeitwerk::Loader.for_gem_extension(Net::HTTP) loader.setup ``` -------------------------------- ### Configure nsfile for Explicit Namespaces Source: https://github.com/fxn/zeitwerk/blob/main/README.md Set the nsfile before calling setup to define explicit namespaces within directories. The nsfile must be a non-hidden basename with a .rb extension. ```ruby loader.nsfile = 'ns.rb' # must be set before setup ``` -------------------------------- ### Zeitwerk Loader for Gem Setup Source: https://github.com/fxn/zeitwerk/blob/main/README.md A convenience shortcut for gems with code organized under the `lib` directory. It configures the loader with appropriate tag, inflector, and root directory. ```ruby # lib/my_gem.rb require 'zeitwerk' loader = Zeitwerk::Loader.new loader.tag = File.basename(__FILE__, '.rb') loader.inflector = Zeitwerk::GemInflector.new(__FILE__) loader.push_dir(File.dirname(__FILE__)) ``` -------------------------------- ### Zeitwerk::Loader#all_expected_cpaths Example Source: https://github.com/fxn/zeitwerk/blob/main/README.md Illustrates the output of Zeitwerk::Loader#all_expected_cpaths, mapping file paths to their expected constant paths. Ignored files, hidden files, and directories without '.rb' files are excluded. ```ruby { '/.../lib' => 'Object', '/.../lib/my_gem.rb' => 'MyGem', '/.../lib/my_gem' => 'MyGem', '/.../lib/my_gem/version.rb' => 'MyGem::VERSION', '/.../lib/my_gem/drivers' => 'MyGem::Drivers', '/.../lib/my_gem/drivers/unix.rb' => 'MyGem::Drivers::Unix', '/.../lib/my_gem/drivers/windows.rb' => 'MyGem::Drivers::Windows', '/.../lib/my_gem/collapsed' => 'MyGem', '/.../lib/my_gem/collapsed/foo.rb' => 'MyGem::Foo' } ``` -------------------------------- ### Get Root Directories Source: https://github.com/fxn/zeitwerk/blob/main/README.md Retrieve an array of absolute paths for the root directories managed by the loader. Use the 'namespaces: true' option to get a hash of paths to their corresponding namespaces. ```ruby loader = Zeitwerk::Loader.new loader.push_dir(Pathname.new('/foo')) loader.dirs # => ['/foo'] ``` ```ruby loader = Zeitwerk::Loader.new loader.push_dir(Pathname.new('/foo')) loader.push_dir(Pathname.new('/bar'), namespace: Bar) loader.dirs(namespaces: true) # => { '/foo' => Object, '/bar' => Bar } ``` -------------------------------- ### Gem Inflector Structure Source: https://github.com/fxn/zeitwerk/blob/main/README.md Example of structuring a custom inflector within a gem, using `Zeitwerk::GemInflector` and ensuring proper module definition order. ```ruby # lib/my_gem/inflector.rb module MyGem class Inflector < Zeitwerk::GemInflector ... end end # lib/my_gem.rb require 'zeitwerk' require_relative 'my_gem/inflector' loader = Zeitwerk::Loader.for_gem loader.inflector = MyGem::Inflector.new(__FILE__) loader.setup module MyGem # ... end ``` ```ruby # Correct, effectively defines MyGem. module MyGem class Inflector < Zeitwerk::GemInflector # ... end end ``` ```ruby # Raises uninitialized constant MyGem (NameError). class MyGem::Inflector < Zeitwerk::GemInflector # ... end ``` -------------------------------- ### Custom Inflection Rule Example Source: https://github.com/fxn/zeitwerk/blob/main/README.md Apply a custom inflection rule to map a file name to a specific constant name when Zeitwerk's default convention doesn't match. ```ruby loader.inflector.inflect('max_retries' => 'MAX_RETRIES') ``` -------------------------------- ### Defining Inner Constants (Regular Way) Source: https://github.com/fxn/zeitwerk/blob/main/README.md Example of defining a constant within a class, which Zeitwerk handles without custom inflection rules. ```ruby # http_crawler.rb class HttpCrawler MAX_RETRIES = 10 end ``` -------------------------------- ### Defining Inner Constants (Custom Inflection) Source: https://github.com/fxn/zeitwerk/blob/main/README.md Example of defining a constant within a namespace that requires a custom inflection rule for Zeitwerk. ```ruby # http_crawler/max_retries.rb HttpCrawler::MAX_RETRIES = 10 ``` -------------------------------- ### Define Explicit Namespace in nsfile Source: https://github.com/fxn/zeitwerk/blob/main/README.md An example of defining explicit namespaces using an nsfile within a directory. The file basename maps to the namespace. ```ruby my_component/ns.rb -> MyComponent my_component/widget.rb -> MyComponent::Widget ``` -------------------------------- ### Assigning a Custom Inflector Source: https://github.com/fxn/zeitwerk/blob/main/README.md Assign an instance of your custom inflector to the loader before calling `setup`. This ensures Zeitwerk uses your custom logic for file and directory inflection. ```ruby loader.inflector = MyInflector.new ``` -------------------------------- ### Handling Circular Dependencies in Ruby Source: https://github.com/fxn/zeitwerk/blob/main/README.md This example illustrates a circular dependency where class `C` inherits from `D`, and class `D` references `C`. Such dependencies are not supported by Zeitwerk. ```ruby # c.rb class C < D end ``` ```ruby # d.rb class D C end ``` -------------------------------- ### Custom Inflector Definition Source: https://github.com/fxn/zeitwerk/blob/main/README.md Define a custom inflector by subclassing `Zeitwerk::Inflector` and overriding methods like `camelize`. This example customizes camelization for HTML-related basenames. ```ruby class MyInflector < Zeitwerk::Inflector def camelize(basename, abspath) if basename =~ /\Ahtml_(.*)/ 'HTML' + super($1, abspath) else super end end end ``` -------------------------------- ### Using the on_load Callback Source: https://github.com/fxn/zeitwerk/blob/main/README.md Schedule code to run when a specific file is loaded by Zeitwerk. The callback receives the loaded class and its absolute path as arguments. ```ruby class SomeApiClient class << self attr_accessor :endpoint end end ``` ```ruby # config/environments/development.rb loader.on_load('SomeApiClient') do |klass, _abspath| klass.endpoint = 'https://api.dev' end ``` -------------------------------- ### Run Zeitwerk Test Suite Source: https://github.com/fxn/zeitwerk/blob/main/README.md Execute the entire test suite for Zeitwerk from the project root. ```shell bin/test ``` -------------------------------- ### Enable Loader Logging to STDOUT Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use the `log!` method for a quick way to enable loader activity tracing to standard output. This is primarily for troubleshooting. ```ruby loader.log! ``` -------------------------------- ### Eager Load All Code Source: https://github.com/fxn/zeitwerk/blob/main/README.md Load all project code upfront. This can be useful for ensuring all code is available immediately. ```ruby loader.eager_load ``` -------------------------------- ### Run All Tests with Mise Source: https://github.com/fxn/zeitwerk/blob/main/AGENTS.md Execute the entire test suite using the `mise exec` command. ```bash mise exec -- bin/test ``` -------------------------------- ### Configure nsfile to 'index.rb' Source: https://github.com/fxn/zeitwerk/blob/main/README.md When the nsfile is set to 'index.rb', any 'index.rb' file in a directory must define the directory's namespace, not a nested 'Index' namespace. ```ruby loader.nsfile = 'index.rb' ``` -------------------------------- ### Zeitwerk File Naming Convention Source: https://github.com/fxn/zeitwerk/blob/main/README.md Illustrates the conventional mapping between file paths and constant names for Zeitwerk autoloading. ```plaintext lib/my_gem.rb -> MyGem lib/my_gem/foo.rb -> MyGem::Foo lib/my_gem/bar_baz.rb -> MyGem::BarBaz lib/my_gem/woo/zoo.rb -> MyGem::Woo::Zoo ``` -------------------------------- ### Focus and Run Individual Test Source: https://github.com/fxn/zeitwerk/blob/main/README.md Mark an individual test with 'focus' to run only that specific test using the 'bin/test' command. ```ruby focus test 'capitalizes the first letter' do assert_equal 'User', camelize('user') end ``` -------------------------------- ### Using Zeitwerk::NullInflector Source: https://github.com/fxn/zeitwerk/blob/main/README.md Instantiate Zeitwerk::NullInflector to use an inflector that returns input unchanged. This is experimental. ```ruby loader.inflector = Zeitwerk::NullInflector.new ``` -------------------------------- ### Exact Basename Matching for Inflection Source: https://github.com/fxn/zeitwerk/blob/main/README.md Demonstrates how exact basename matches are used for inflection. Partial matches are ignored. ```ruby loader.inflector.inflect('xml' => 'XML') ``` -------------------------------- ### NullInflector File and Directory Naming Convention Source: https://github.com/fxn/zeitwerk/blob/main/README.md With NullInflector, file and directory names directly correspond to the constants they define. ```text User.rb -> User HTMLParser.rb -> HTMLParser Admin/Role.rb -> Admin::Role ``` -------------------------------- ### Gem Extension Entry Point Require Source: https://github.com/fxn/zeitwerk/blob/main/README.md For gem extensions, the entry point file (e.g., lib/net/http/niche_feature.rb) must be loaded with `Kernel#require`. ```ruby # For technical reasons, this cannot be require_relative. require 'net/http/niche_feature' ``` -------------------------------- ### Collapse Directories Using Glob Patterns Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use glob patterns with `collapse` to manage multiple directories that should not be treated as namespaces. Patterns are expanded on add and reload. ```ruby loader.collapse("#{__dir__}/*/actions") ``` -------------------------------- ### Run Specific Test Line with Mise Source: https://github.com/fxn/zeitwerk/blob/main/AGENTS.md Execute a specific test by providing the file path and line number. ```bash mise exec -- bin/test : ``` -------------------------------- ### Explicit Namespaces with Collapsed Directories Source: https://github.com/fxn/zeitwerk/blob/main/README.md Demonstrates defining explicit namespaces when certain directories are collapsed and ignored. The nsfile in a collapsed directory still defines the parent namespace. ```ruby my_component/src/ns.rb -> MyComponent my_component/src/widget.rb -> MyComponent::Widget my_component/assets/widget.js my_component/tests/test_widget.rb ``` -------------------------------- ### Execute Ruby Tools with Mise Source: https://github.com/fxn/zeitwerk/blob/main/AGENTS.md Run various Ruby development tools, such as linters or formatters, using `mise exec`. ```bash mise exec -- ``` -------------------------------- ### Load Individual File with Zeitwerk Loader Source: https://github.com/fxn/zeitwerk/blob/main/README.md Loads an individual Ruby file using the Zeitwerk loader. Useful when the loader is not eager loading the entire project. ```ruby loader.load_file("#{__dir__}/custom_web_app/routes.rb") ``` -------------------------------- ### Execute Code When Any Constant is Loaded Source: https://github.com/fxn/zeitwerk/blob/main/README.md This catch-all callback executes for any constant managed by the loader. The block receives the constant path, its value, and its absolute path. Use this for debugging or global actions, though specific callbacks are preferred for clarity. ```ruby loader.on_load do |cpath, value, abspath| # ... end ``` -------------------------------- ### Eager Load a Specific Directory Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use `eager_load_dir` to recursively load all files within a specified directory. This is helpful when not eager loading the entire project but needing a specific subtree to be loaded. ```ruby loader.eager_load_dir("#{__dir__}/custom_web_app/routes") ``` -------------------------------- ### Run Specific Test File with Mise Source: https://github.com/fxn/zeitwerk/blob/main/AGENTS.md Execute tests within a particular file by specifying the file path. ```bash mise exec -- bin/test ``` -------------------------------- ### Eager Load Namespace with Zeitwerk Source: https://github.com/fxn/zeitwerk/blob/main/README.md Broadcasts eager_load_namespace to all loaders. Useful for shared namespaces in frameworks with plugins. ```ruby Zeitwerk::Loader.eager_load_namespace(MyFramework::Routes) ``` -------------------------------- ### Default Root Namespace Mapping Source: https://github.com/fxn/zeitwerk/blob/main/README.md Shows the expected constant definitions for files within directories configured with the default root namespace (`Object`). ```plaintext models/user.rb -> User serializers/user_serializer.rb -> UserSerializer ``` -------------------------------- ### Default Root Namespace Configuration Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure Zeitwerk to use the top-level `Object` namespace for files in specified directories. ```ruby loader.push_dir("#{__dir__}/models") loader.push_dir("#{__dir__}/serializers") ``` -------------------------------- ### Execute Code When a Specific Constant is Loaded Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use this callback to execute code after a specific constant (e.g., a class or module) is loaded. The block receives the constant's value and its absolute path. This is useful for initializing or configuring classes upon loading. ```ruby loader.on_load('SomeApiClient') do |klass, _abspath| klass.endpoint = 'https://api.prod' end ``` -------------------------------- ### Ignore Database Adapters with Zeitwerk Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use `loader.ignore` to prevent Zeitwerk from autoloading specific directories, such as database adapters, when they are not immediately needed. The adapter must be required manually. ```ruby db_adapters = "#{__dir__}/my_gem/db_adapters" loader.ignore(db_adapters) loader.setup ``` ```ruby require "my_gem/db_adapters/#{config[:db_adapter]}" ``` -------------------------------- ### Run Specific Zeitwerk Test Suite Source: https://github.com/fxn/zeitwerk/blob/main/README.md Run a particular test suite by passing its file name as an argument to the test runner. ```shell bin/test test/lib/zeitwerk/test_eager_load.rb ``` -------------------------------- ### Collect Autoloaded Constants Source: https://github.com/fxn/zeitwerk/blob/main/README.md Register a callback to collect constant paths and values as they are loaded by Zeitwerk. This is useful for introspection but should be used sparingly to minimize memory footprint. ```ruby autoloaded_cpaths = [] loader.on_load do |cpath, _value, _abspath| autoloaded_cpaths << cpath end ``` -------------------------------- ### Broadcast Eager Load to All Loaders Source: https://github.com/fxn/zeitwerk/blob/main/README.md Initiate an eager load across all Zeitwerk loader instances active in the process. ```ruby Zeitwerk::Loader.eager_load_all ``` -------------------------------- ### Eager Load a Namespace Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use `eager_load_namespace` to recursively load all files associated with a given namespace (class or module). This is useful when only a specific part of the project needs to be loaded. ```ruby loader.eager_load_namespace(MyApp::Routes) ``` -------------------------------- ### Ignore Directory Source: https://github.com/fxn/zeitwerk/blob/main/README.md Instruct Zeitwerk to ignore an entire directory and its contents by passing the directory path to the `ignore` method. Files within this directory will not be autoloaded. ```ruby core_ext = "#{__dir__}/my_gem/core_ext" loader.ignore(core_ext) loader.setup ``` -------------------------------- ### Collapse Directory for Organization Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure Zeitwerk to collapse a directory, preventing it from being treated as a namespace. This is useful for organizational subdirectories. ```ruby loader.collapse("#{__dir__}/booking/actions") ``` -------------------------------- ### Gem Extension Version Definition Source: https://github.com/fxn/zeitwerk/blob/main/README.md This snippet shows the conventional location and content for defining the version of a gem extension. ```ruby module Net::HTTP::NicheFeature VERSION = '1.0.0' end ``` -------------------------------- ### Zeitwerk Shadowing: File Ignored Due to Precedence Source: https://github.com/fxn/zeitwerk/blob/main/README.md This log message indicates that a file was ignored because another file with the same name in a higher-priority directory already defined the constant. ```ruby file #{file} is ignored because #{previous_occurrence} has precedence ``` -------------------------------- ### Execute Code When Any Constant is Unloaded Source: https://github.com/fxn/zeitwerk/blob/main/README.md This catch-all callback executes for any constant managed by the loader when it is unloaded. The block receives the constant path, its value, and its absolute path. Use with caution, as the unloading context is unstable. ```ruby loader.on_unload do |cpath, value, abspath| # ... end ``` -------------------------------- ### Handling Partial Matches with Additional Overrides Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure additional overrides to handle cases where partial matches need specific inflection rules. ```ruby loader.inflector.inflect( 'xml' => 'XML', 'xml_parser' => 'XMLParser' ) ``` -------------------------------- ### Check Filesystem Encoding Source: https://github.com/fxn/zeitwerk/blob/main/README.md Determines the filesystem encoding of the Ruby environment. Zeitwerk supports UTF-8 encoded filesystems. ```shell % ruby -e "puts Encoding.find('filesystem')" ``` -------------------------------- ### Eager Load for Testing Compliance Source: https://github.com/fxn/zeitwerk/blob/main/README.md Eager load the project in a test suite to verify that all managed files define their expected constants. Catches Zeitwerk::NameError if a constant is missing. ```ruby begin loader.eager_load(force: true) rescue Zeitwerk::NameError => e flunk e.message else assert true end ``` -------------------------------- ### Run Specific Zeitwerk Test with Line Number Source: https://github.com/fxn/zeitwerk/blob/main/README.md Execute a specific test suite and pinpoint a particular line number for execution. ```shell bin/test test/lib/zeitwerk/test_eager_load.rb:52 ``` -------------------------------- ### Configure Logger Object Source: https://github.com/fxn/zeitwerk/blob/main/README.md Assign an object that responds to `debug` (or similar methods) to the loader's logger. This allows integration with existing logging frameworks. ```ruby loader.logger = Logger.new($stderr) ``` ```ruby loader.logger = Rails.logger ``` -------------------------------- ### Custom Root Namespace with ActiveJob Source: https://github.com/fxn/zeitwerk/blob/main/README.md Associates a custom namespace with a specific root directory using `push_dir`. The provided namespace must be non-reloadable. ```ruby require 'active_job' require 'active_job/queue_adapters' loader.push_dir("#{__dir__}/adapters", namespace: ActiveJob::QueueAdapters) ``` -------------------------------- ### Disabling Extra File Warnings Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure Zeitwerk to not warn about extra files in the 'lib' directory when using `for_gem`. ```ruby Zeitwerk::Loader.for_gem(warn_on_extra_files: false) ``` -------------------------------- ### Initialize Read-Write Lock for Thread-Safe Reloading Source: https://github.com/fxn/zeitwerk/blob/main/README.md Initializes a concurrent read-write lock for coordinating thread-safe reloading in a framework. ```ruby require 'concurrent/atomic/read_write_lock' MyFramework::RELOAD_RW_LOCK = Concurrent::ReadWriteLock.new ``` -------------------------------- ### Zeitwerk Shadowing: File Ignored Due to Existing Constant Source: https://github.com/fxn/zeitwerk/blob/main/README.md This log message indicates that a file was ignored because the constant it would define was already present in the Ruby environment. ```ruby file #{file} is ignored because #{constant_path} is already defined ``` -------------------------------- ### Ignore Specific File Source: https://github.com/fxn/zeitwerk/blob/main/README.md Tell Zeitwerk to ignore a specific Ruby file by providing its path to the `ignore` method. This file must then be loaded manually using `require` or `require_relative`. ```ruby kernel_ext = "#{__dir__}/my_gem/core_ext/kernel.rb" loader.ignore(kernel_ext) loader.setup ``` -------------------------------- ### Acquire Read Lock for Serving Requests Source: https://github.com/fxn/zeitwerk/blob/main/README.md Acquires the read lock to safely serve individual requests when Zeitwerk reloading is enabled. ```ruby MyFramework::RELOAD_RW_LOCK.with_read_lock do serve(request) end ``` -------------------------------- ### Ignore Test Files with Zeitwerk Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use `loader.ignore` with a glob pattern to exclude test files from Zeitwerk's autoloading when they are mixed with implementation files. ```ruby tests = "#{__dir__}/**/*_test.rb" loader.ignore(tests) loader.setup ``` -------------------------------- ### Exclude Files/Directories from Eager Loading Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use `do_not_eager_load` to specify paths that should not be eager loaded, even if they are autoloadable. This is useful for dynamic or configuration files. ```ruby db_adapters = "#{__dir__}/my_gem/db_adapters" loader.do_not_eager_load(db_adapters) loader.setup loader.eager_load # won't eager load the database adapters ``` -------------------------------- ### Force Eager Loading Source: https://github.com/fxn/zeitwerk/blob/main/README.md Override eager load exclusions by passing `force: true` to `eager_load`. This ensures that even excluded files are loaded, which can be useful for testing project layout compliance. ```ruby loader.eager_load(force: true) # database adapters are eager loaded ``` -------------------------------- ### Set Global Default Logger Source: https://github.com/fxn/zeitwerk/blob/main/README.md Configure a default logger for all Zeitwerk loaders by assigning a callable to `Zeitwerk::Loader.default_logger`. This affects loaders created subsequently. ```ruby Zeitwerk::Loader.default_logger = method(:puts) ``` -------------------------------- ### Configure Custom Logger Callable Source: https://github.com/fxn/zeitwerk/blob/main/README.md Set a custom logger for the loader by assigning a callable object, such as a method reference or a lambda, that accepts a single message argument. ```ruby loader.logger = method(:puts) ``` ```ruby loader.logger = ->(msg) { ... } ``` -------------------------------- ### Ignoring Extra Files in Gem Autoloading Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use this to tell Zeitwerk to ignore specific files or directories within your gem's 'lib' folder that should not be autoloaded. ```ruby loader.ignore("#{__dir__}/generators") ``` -------------------------------- ### Acquire Write Lock for Triggering Reload Source: https://github.com/fxn/zeitwerk/blob/main/README.md Acquires the write lock to safely trigger a Zeitwerk loader reload. ```ruby MyFramework::RELOAD_RW_LOCK.with_write_lock do loader.reload end ``` -------------------------------- ### Execute Code When a Specific Constant is Unloaded Source: https://github.com/fxn/zeitwerk/blob/main/README.md Use this callback to execute code before a specific constant is unloaded. The block receives the constant's value and its absolute path. This is useful for cleanup tasks, like clearing caches, but avoid referencing other reloadable constants within the block. ```ruby loader.on_unload('Country') do |klass, _abspath| klass.clear_cache end ``` -------------------------------- ### Defining a Custom Inflector Source: https://github.com/fxn/zeitwerk/blob/main/README.md Zeitwerk allows for the configuration of custom inflector classes for more complex inflection needs. ```ruby # Custom inflector logic would go here ``` -------------------------------- ### Declaring Library-Public Internal Methods Source: https://github.com/fxn/zeitwerk/blob/main/PROJECT_RULES.md Use the `internal` DSL to declare methods that are public within the library but not part of the end-user public interface. This is often used for internal helper methods that are aliased with a leading double underscore. ```Ruby internal :autoloads ``` -------------------------------- ### Set Custom Loader Tag Source: https://github.com/fxn/zeitwerk/blob/main/README.md Assign a custom string to `loader.tag` to identify this specific loader in log traces. This is useful when multiple loaders are active. ```ruby loader.tag = 'grep_me' ``` -------------------------------- ### Derive Constant Path from File Path Source: https://github.com/fxn/zeitwerk/blob/main/README.md Determine the expected constant path for a given file or directory relative to the loader's root directories. Returns nil for ignored paths or paths not managed by the loader. Raises Zeitwerk::Error if the path does not exist. ```ruby loader.cpath_expected_at('app/models') # => 'Object' loader.cpath_expected_at('app/models/user.rb') # => 'User' loader.cpath_expected_at('app/models/hotel') # => 'Hotel' loader.cpath_expected_at('app/models/hotel/billing.rb') # => 'Hotel::Billing' ``` ```ruby loader.cpath_expected_at('a/b/collapsed/c') # => 'A::B::C' loader.cpath_expected_at('a/b/collapsed') # => 'A::B', edge case loader.cpath_expected_at('a/b') # => 'A::B' ``` ```ruby loader.cpath_expected_at('non_existing_file.rb') # => Zeitwerk::Error ``` ```ruby loader.cpath_expected_at('8.rb') # => Zeitwerk::NameError ``` -------------------------------- ### Basic Snake Case to Camel Case Inflection Source: https://github.com/fxn/zeitwerk/blob/main/README.md This is the default behavior of Zeitwerk::Inflector, converting snake_case to camelCase. ```text user -> User users_controller -> UsersController html_parser -> HtmlParser ``` -------------------------------- ### Overriding Basename Inflections Source: https://github.com/fxn/zeitwerk/blob/main/README.md Customize camelization for specific basenames. This method can be called multiple times. ```ruby loader.inflector.inflect( 'html_parser' => 'HTMLParser', 'mysql_adapter' => 'MySQLAdapter' ) ``` ```ruby loader.inflector.inflect 'html_parser' => 'HTMLParser' loader.inflector.inflect 'mysql_adapter' => 'MySQLAdapter' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.