I’m facing an issue with a custom generator in Rails 7.1, and it’s been quite confusing. I could really use some help!
I created a custom generator with the following structure after running rails g generator query:
create lib/generators/query
create lib/generators/query/query_generator.rb
create lib/generators/query/USAGE
create lib/generators/query/templates
Here’s the basic structure of my generator:
class QueryGenerator < Rails::Generators::NamedBase
source_root File.expand_path("templates", __dir__)
# rest of the code
end
Everything works perfectly in my development environment. I can run rails generate query user without any issues.
However, when deploying to production with Dokku, I encountered two major errors:
-
NameError: Uninitialized constant Rails::Generators
This was triggered by the QueryGenerator class. I fixed it by adding require ‘rails/generators’ at the top of lib/generators/query/query_generator.rb. -
Zeitwerk::NameError: Expected file to define constant Generators::Query::QueryGenerator
To resolve this, I adjusted the structure as follows:
require 'rails/generators'
module Generators
module Query
class QueryGenerator < Rails::Generators::NamedBase
# ... rest of the code ...
end
end
end
After making these changes, running RAILS_ENV=production bin/rails zeitwerk:check showed no errors, which seemed promising.
Despite everything appearing to work, when I try to run the generator with rails g query User, I get the following error:
Could not find generator 'query'. (Rails::Command::CorrectableNameError)
Run `bin/rails generate --help` for more options.
It seems like there’s a conflict between how Zeitwerk expects things to be loaded and how Rails is recognizing the generator.
Has anyone encountered something similar or have any ideas on how to resolve this? I’d appreciate any advice or guidance. Thanks in advance!
Solution
Hey everyone, I managed to solve the issue I was facing! 🎉
I fixed it by changing the file structure from:
lib/generators/query/query_generator.rb
lib/generators/query/templates/query.rb.tt
To:
lib/rails/generators/query_generator.rb
lib/rails/generators/templates/query.rb.tt
And I updated the generator code as follows:
# frozen_string_literal: true
require 'rails/generators'
module Rails
module Generators
class QueryGenerator < Rails::Generators::NamedBase
# Your code here...
end
end
end
This new structure and code resolved the issue in production, and the generator now works as expected.