Skip to content

Load the gem outside Rails with Zeitwerk - #1080

Open
pcbeingused333 wants to merge 4 commits into
patterns-ai-core:mainfrom
pcbeingused333:load-without-rails
Open

pcbeingused333 wants to merge 4 commits into
patterns-ai-core:mainfrom
pcbeingused333:load-without-rails

Conversation

@pcbeingused333

Copy link
Copy Markdown
Contributor

Since the move to Rails::Engine (#1003, not released yet: 0.19.5 predates it), main only loads inside a booted Rails app:

  • In a plain Ruby script, following the README's require "langchain" raises NameError: uninitialized constant Rails from lib/langchain/engine.rb.
  • With require "rails" first but no app booted, require "langchain" succeeds, but Langchain::LLM is undefined, because only the engine sets up autoloading.

So the next release would break scripts, Sinatra/Hanami apps, background workers outside Rails, and the gems that depend on langchainrb (#880's case).

Change

lib/langchain.rb requires the engine when Rails::Engine is defined, as now. Otherwise it sets up Zeitwerk::Loader.for_gem, the loader the gem used before #1003, with the acronyms from config/initializers/inflections.rb. It ignores engine.rb and application_record.rb, which need Rails. Nothing changes for Rails apps.

rails stays a runtime dependency in the gemspec. It is installed but not loaded outside Rails. Making it optional would be a separate decision.

Tests

  • New spec in spec/langchain_spec.rb: a subprocess runs require "langchain" without Rails, checks that Rails wasn't loaded, eager-loads every class (Zeitwerk::Loader.eager_load_all) and resolves Langchain::LLM::OpenAI and Langchain::LLM::Response::OpenAIResponse. It fails on main with the NameError above.
  • Locally I also eager-loaded all 112 Langchain:: classes without Rails and instantiated Langchain::LLM::Ollama.
  • bundle exec rspec: 770 examples, 0 failures (this exercises the engine path through test/dummy). standardrb is clean.

🤖 Generated with Claude Code

pcbeingused333 and others added 4 commits October 15, 2026 15:04
Since the move to Rails::Engine (patterns-ai-core#1003), require "langchain" raised
NameError (uninitialized constant Rails) in a plain Ruby script, and
with Rails loaded but no app booted nothing under Langchain:: was
autoloaded. When Rails::Engine isn't defined, set up a Zeitwerk loader
with the acronyms from config/initializers/inflections.rb instead.
Rails apps still get the engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant