Fix Env#current Rails.env call without defined?(Rails) guard#963
Fix Env#current Rails.env call without defined?(Rails) guard#963
Conversation
Shakapacker::Env#current calls Rails.env directly, which raises NameError when Shakapacker.config is accessed from a non-Rails Ruby process (e.g., react_on_rails' bin/dev). The error gets rescued up the chain, causing silent fallback to "production" instead of resolving the correct environment from RAILS_ENV/RACK_ENV env vars. This follows the same pattern established in PR #681 for Instance#initialize, and mirrors how Runner#initialize already resolves the environment via env vars. Fixes #962 Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughGuard Rails access in Shakapacker::Env: Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
ReviewThe fix is correct and necessary — A few issues worth addressing before merge: Test isolation (
|
Greptile SummaryThis PR safely fixes a Changes:
The pattern is consistent with existing usage in Confidence Score: 5/5
Last reviewed commit: 79ac745 |
There was a problem hiding this comment.
🧹 Nitpick comments (2)
lib/shakapacker/env.rb (1)
29-35: Minor inconsistency with.presenceusage.Line 33 uses raw
||fallback without.presence, whereas line 24 incurrentuses.presence. IfENV["RAILS_ENV"]is an empty string"", this would log"RAILS_ENV= environment is not defined"rather than falling back to RACK_ENV or "(unknown)".This is a minor cosmetic inconsistency—the functionality is correct since this is only for logging. Consider adding
.presencefor consistency if desired.♻️ Optional: Add `.presence` for consistency
def fallback_env_warning env_value = if defined?(Rails) && Rails.respond_to?(:env) Rails.env else - ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "(unknown)" + ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "(unknown)" end logger.info "RAILS_ENV=#{env_value} environment is not defined in #{config_path}, falling back to #{FALLBACK_ENV} environment" end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/shakapacker/env.rb` around lines 29 - 35, In fallback_env_warning, ensure the ENV lookups mirror the .presence usage from current: change how env_value is derived in the fallback branch so ENV["RAILS_ENV"] and ENV["RACK_ENV"] use .presence (e.g., ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "(unknown)") so empty strings fall through and the logged value is consistent with current's behavior; update only the env_value expression inside the fallback_env_warning method.spec/shakapacker/env_without_rails_spec.rb (1)
31-33: Usehide_constinstead ofstub_const("Rails", nil)for accuracy.The context describes "when Rails is not defined," but
stub_const("Rails", nil)keeps Rails defined (asnil). After stubbing:
defined?(Rails)returns"constant"(truthy)- The test passes because
nil.respond_to?(:env)returns falseUsing
hide_const("Rails")truly undefines the constant, makingdefined?(Rails)returnnil(falsy), which more accurately tests the intended scenario.♻️ Use hide_const for accurate simulation
before do - stub_const("Rails", nil) if defined?(Rails) + hide_const("Rails") if defined?(Rails) end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@spec/shakapacker/env_without_rails_spec.rb` around lines 31 - 33, Replace the current use of stub_const("Rails", nil) in the before block with hide_const("Rails") so the Rails constant is actually undefined during the example; update the setup inside the before hook that references stub_const to call hide_const("Rails") instead, ensuring defined?(Rails) returns nil and the spec "when Rails is not defined" accurately exercises the code paths that rely on Rails being absent.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@lib/shakapacker/env.rb`:
- Around line 29-35: In fallback_env_warning, ensure the ENV lookups mirror the
.presence usage from current: change how env_value is derived in the fallback
branch so ENV["RAILS_ENV"] and ENV["RACK_ENV"] use .presence (e.g.,
ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "(unknown)") so empty
strings fall through and the logged value is consistent with current's behavior;
update only the env_value expression inside the fallback_env_warning method.
In `@spec/shakapacker/env_without_rails_spec.rb`:
- Around line 31-33: Replace the current use of stub_const("Rails", nil) in the
before block with hide_const("Rails") so the Rails constant is actually
undefined during the example; update the setup inside the before hook that
references stub_const to call hide_const("Rails") instead, ensuring
defined?(Rails) returns nil and the spec "when Rails is not defined" accurately
exercises the code paths that rely on Rails being absent.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 45433614-003f-4941-a58a-6a8595f370de
📒 Files selected for processing (2)
lib/shakapacker/env.rbspec/shakapacker/env_without_rails_spec.rb
…gger
When no RAILS_ENV or RACK_ENV is set (common in non-Rails scripts), fall
back to DEFAULT_ENV ("development") instead of nil. This matches the
pattern in Runner#initialize which uses the same fallback chain.
Also add rescue to fallback_env_warning for logger failures — without
full Rails, ActiveSupport::IsolatedExecutionState may not be available,
causing the TaggedLogging logger to crash.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
ReviewThe core fix is correct and well-motivated — adding a Two issues need to be addressed before merging: 1. Tests do not actually cover the intended code path
2. The rescue block in The rescue catches Minor The env-resolution logic is duplicated between |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
spec/shakapacker/env_without_rails_spec.rb (1)
53-55: Exercise the fallback-warning branch in this example.With both env vars unset,
currentresolves to"development", and that key exists in this fixture, sofallback_env_warningnever runs. That leaves the newly guarded non-Rails warning path untested. Using a missing env such as"staging"here would cover the actual regression path and verify thatinquirefalls back to"production"without raising.If you also assert the warning emission, prefer a spy + `have_received`. As per coding guidelines, `**/*_spec.rb`: Use explicit RSpec spy assertions with `have_received`/`not_to have_received` instead of indirect counter patterns.💡 Suggested spec
- it "does not raise NameError" do - stub_const("ENV", ENV.to_h.merge("RAILS_ENV" => nil, "RACK_ENV" => nil)) - expect { Shakapacker::Env.inquire(instance) }.not_to raise_error + it "falls back to production without raising when the env is missing from config" do + stub_const("ENV", ENV.to_h.merge("RAILS_ENV" => "staging", "RACK_ENV" => nil)) + + resolved_env = nil + expect { resolved_env = Shakapacker::Env.inquire(instance) }.not_to raise_error + expect(resolved_env).to eq "production" end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@spec/shakapacker/env_without_rails_spec.rb` around lines 53 - 55, The test should exercise the fallback-warning branch by stubbing ENV so current resolves to a missing key (e.g., "staging") instead of defaulting to "development"; change the stub_const call used around Shakapacker::Env.inquire(instance) to set RAILS_ENV or RACK_ENV to "staging" (or another absent fixture key) so that Shakapacker::Env.inquire triggers the fallback to "production" and runs fallback_env_warning and the non-Rails warning path; also, if asserting the warning, replace indirect counters with an RSpec spy and use have_received to assert the warning method was invoked.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/shakapacker/env.rb`:
- Around line 20-39: The fallback_env_warning should reuse the same environment
resolution logic as current to avoid mismatched/blank RAILS_ENV reporting: call
or replicate the resolver used in current (respecting presence and
available_environments) to obtain the effective env and log a neutral label
(e.g., "environment" or "Rails/Rack environment") rather than hard-coding
"RAILS_ENV="; update fallback_env_warning to derive env_value from current (or
the same ENV presence logic) and interpolate that in both logger.info and the
puts in the rescue block so the message accurately reflects the resolved
environment.
---
Nitpick comments:
In `@spec/shakapacker/env_without_rails_spec.rb`:
- Around line 53-55: The test should exercise the fallback-warning branch by
stubbing ENV so current resolves to a missing key (e.g., "staging") instead of
defaulting to "development"; change the stub_const call used around
Shakapacker::Env.inquire(instance) to set RAILS_ENV or RACK_ENV to "staging" (or
another absent fixture key) so that Shakapacker::Env.inquire triggers the
fallback to "production" and runs fallback_env_warning and the non-Rails warning
path; also, if asserting the warning, replace indirect counters with an RSpec
spy and use have_received to assert the warning method was invoked.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: f8537ec3-47b0-4d92-904e-5c5c8813b28d
📒 Files selected for processing (2)
lib/shakapacker/env.rbspec/shakapacker/env_without_rails_spec.rb
resolve_hook_script_path required Rails.root to resolve hook script paths, returning nil in bin/dev context where Rails isn't loaded. This caused hook_configured? to return false even when the hook was properly configured, leading to redundant pack generation after the hook already ran. Add project_root helper that falls back to BUNDLE_GEMFILE dirname (set by Bundler during require "bundler/setup") or Dir.pwd when Rails.root is unavailable. Companion to shakacode/shakapacker#963 which fixes Shakapacker::Env to work without Rails. Together these two fixes fully resolve #2438 without the YAML-parsing workaround in #2561. Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Use hide_const("Rails") instead of stub_const("Rails", nil) so
defined?(Rails) is actually nil, testing the full guard path
- Add .presence to ENV lookups in fallback_env_warning to match current
- Fix comment: rescue falls back to puts, not "silently"
- Replace no-raise test with one that exercises fallback_env_warning by
using RAILS_ENV=staging (missing from fixture config)
Co-Authored-By: Claude Opus 4.6 <[email protected]>
ReviewThe fix is on the right track — adding a 🔴 Bug:
|
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
lib/shakapacker/env.rb (1)
30-39:⚠️ Potential issue | 🟡 MinorReuse the same resolver in
fallback_env_warning.Line 24 falls back to
Shakapacker::DEFAULT_ENV, but Lines 33-39 still collapse that case to"(unknown)"and log it asRAILS_ENV=.... In the no-Rails/no-ENV path, the warning can still report the wrong requested environment.💡 Proposed fix
def current - env = if defined?(Rails) && Rails.respond_to?(:env) - Rails.env.to_s - else - ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || Shakapacker::DEFAULT_ENV - end - env.presence_in(available_environments)&.inquiry + resolved_env.presence_in(available_environments)&.inquiry end def fallback_env_warning - env_value = if defined?(Rails) && Rails.respond_to?(:env) - Rails.env - else - ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "(unknown)" - end - logger.info "RAILS_ENV=#{env_value} environment is not defined in #{config_path}, falling back to #{FALLBACK_ENV} environment" + env_value = resolved_env + logger.info "environment=#{env_value} is not defined in #{config_path}, falling back to #{FALLBACK_ENV} environment" rescue NameError, NoMethodError - puts "RAILS_ENV=#{env_value} environment is not defined in #{config_path}, falling back to #{FALLBACK_ENV} environment" + puts "environment=#{env_value} is not defined in #{config_path}, falling back to #{FALLBACK_ENV} environment" end + + def resolved_env + if defined?(Rails) && Rails.respond_to?(:env) + Rails.env.to_s + else + ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || Shakapacker::DEFAULT_ENV + end + end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/shakapacker/env.rb` around lines 30 - 39, The fallback_env_warning currently builds env_value that uses "(unknown)" when neither Rails.env nor ENV vars are present, causing the warning to misreport the actual fallback; update fallback_env_warning to reuse the same resolver used elsewhere (Shakapacker::DEFAULT_ENV / FALLBACK_ENV) by computing env_value with Rails.env if available, else ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || Shakapacker::DEFAULT_ENV (or FALLBACK_ENV) and then use that env_value in both logger.info and the puts fallback so the logged message shows the real fallback environment; adjust references to env_value, FALLBACK_ENV, Shakapacker::DEFAULT_ENV, fallback_env_warning, config_path, logger and puts accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@lib/shakapacker/env.rb`:
- Around line 21-26: The current method is returning a plain String
(Rails.env.to_s) so inquire returns that String instead of an
ActiveSupport::StringInquirer; change current to return a StringInquirer in both
branches: when Rails.env exists call Rails.env.inquiry (not to_s), and when
falling back use (ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence ||
Shakapacker::DEFAULT_ENV).to_s.inquiry (or use ActiveSupport::StringInquirer.new
on the chosen value) so that inquire (which returns current ||
FALLBACK_ENV.inquiry) always yields an object that responds to env.development?
/ env.production?; keep usage of available_environments/presence_in unchanged.
---
Duplicate comments:
In `@lib/shakapacker/env.rb`:
- Around line 30-39: The fallback_env_warning currently builds env_value that
uses "(unknown)" when neither Rails.env nor ENV vars are present, causing the
warning to misreport the actual fallback; update fallback_env_warning to reuse
the same resolver used elsewhere (Shakapacker::DEFAULT_ENV / FALLBACK_ENV) by
computing env_value with Rails.env if available, else ENV["RAILS_ENV"].presence
|| ENV["RACK_ENV"].presence || Shakapacker::DEFAULT_ENV (or FALLBACK_ENV) and
then use that env_value in both logger.info and the puts fallback so the logged
message shows the real fallback environment; adjust references to env_value,
FALLBACK_ENV, Shakapacker::DEFAULT_ENV, fallback_env_warning, config_path,
logger and puts accordingly.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 9d0ea945-eb8a-428a-9d34-c4621bfa033d
📒 Files selected for processing (2)
lib/shakapacker/env.rbspec/shakapacker/env_without_rails_spec.rb
🚧 Files skipped from review as they are similar to previous changes (1)
- spec/shakapacker/env_without_rails_spec.rb
- Remove unnecessary .to_s on Rails.env that was dropping the StringInquirer type, breaking env.development? predicates - Wrap inquire return with .inquiry so both Rails and non-Rails paths always return ActiveSupport::StringInquirer - Fix if/else/end indentation to match RuboCop variable alignment Co-Authored-By: Claude Opus 4.6 <[email protected]>
ReviewThe fix correctly addresses the root cause: The A few things worth addressing before merging:
No security or performance concerns. |
There was a problem hiding this comment.
♻️ Duplicate comments (1)
lib/shakapacker/env.rb (1)
30-34:⚠️ Potential issue | 🟡 MinorUse the same final default in the warning path.
When neither
RAILS_ENVnorRACK_ENVis set,currentstill triesShakapacker::DEFAULT_ENVbefore falling back.fallback_env_warningreports"(unknown)"in that same case, so the warning can disagree with the env that was actually checked.💡 Suggested change
env_value = if defined?(Rails) && Rails.respond_to?(:env) Rails.env else - ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || "(unknown)" + ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence || Shakapacker::DEFAULT_ENV end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/shakapacker/env.rb` around lines 30 - 34, The warning message can disagree with the actual environment check because env_value falls back to Shakapacker::DEFAULT_ENV before "(unknown)"; update the fallback_env_warning logic to use the same final default (Shakapacker::DEFAULT_ENV) instead of the literal "(unknown)" so the warning matches env_value's resolution (referencing env_value, Shakapacker::DEFAULT_ENV, and fallback_env_warning to locate and change the code).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Duplicate comments:
In `@lib/shakapacker/env.rb`:
- Around line 30-34: The warning message can disagree with the actual
environment check because env_value falls back to Shakapacker::DEFAULT_ENV
before "(unknown)"; update the fallback_env_warning logic to use the same final
default (Shakapacker::DEFAULT_ENV) instead of the literal "(unknown)" so the
warning matches env_value's resolution (referencing env_value,
Shakapacker::DEFAULT_ENV, and fallback_env_warning to locate and change the
code).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 41a75948-b0c6-4a6f-b820-2a605a02052d
📒 Files selected for processing (1)
lib/shakapacker/env.rb
The warning message used "(unknown)" when no env vars were set, but current resolves to DEFAULT_ENV in that case. Align so the warning accurately reports what env was attempted. Co-Authored-By: Claude Opus 4.6 <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
lib/shakapacker/env.rb (1)
14-16: Cachecurrentonce ininquire.
currentconsultsavailable_environments, so line 15 and line 16 currently resolve the environment twice. Reusing a local keeps the warning path and return value tied to the same lookup and avoids the extra YAML load.♻️ Proposed change
def inquire - fallback_env_warning if config_path.exist? && !current - (current || FALLBACK_ENV).inquiry + env = current + fallback_env_warning if config_path.exist? && !env + (env || FALLBACK_ENV).inquiry end🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@lib/shakapacker/env.rb` around lines 14 - 16, The inquire method calls current twice causing duplicate lookups; cache the result in a local variable (e.g., env = current) at the start of inquire, call fallback_env_warning if config_path.exist? && !env, and return (env || FALLBACK_ENV).inquiry so both the warning path and returned value use the same lookup and avoid reloading YAML from available_environments.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@lib/shakapacker/env.rb`:
- Around line 14-16: The inquire method calls current twice causing duplicate
lookups; cache the result in a local variable (e.g., env = current) at the start
of inquire, call fallback_env_warning if config_path.exist? && !env, and return
(env || FALLBACK_ENV).inquiry so both the warning path and returned value use
the same lookup and avoid reloading YAML from available_environments.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 537d8b9e-5cc9-489d-8e45-ba571b5edd4c
📒 Files selected for processing (1)
lib/shakapacker/env.rb
|
Review: The fix is sound and addresses the root cause. Rails.env was called unconditionally in non-Rails processes. Detailed inline comments have been posted. Summary of concerns: (1) code duplication between current and fallback_env_warning - extract a resolve_env helper; (2) NODE_ENV is omitted from the fallback chain while Runner#initialize uses it - inconsistency worth aligning; (3) rescue NameError/NoMethodError is too broad and could hide real bugs - add raise if defined?(Rails) to scope it; (4) spec nits: nil ENV values are unidiomatic, and the fixture file path risks parallel-test collisions. Overall: correct and needed change, these are polish items rather than blockers. |
Co-Authored-By: Claude Opus 4.6 <[email protected]>
## Summary - Added [Unreleased] changelog entries for two merged PRs missing from CHANGELOG.md: - **PR #963**: Fixed `Env#current` crashing when Rails is not loaded (bug fix by @ihabadham) - **PR #900**: Added Node package API documentation (by @justin808) - Skipped non-user-visible PRs: #958, #957, #959 ## Test plan - [x] `yarn lint` passes - [x] Changelog formatting matches existing conventions 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Low Risk** > Documentation-only change confined to `CHANGELOG.md`, with no runtime or build behavior impact. > > **Overview** > Updates `CHANGELOG.md` under **[Unreleased]** to document two previously-merged changes: a fix preventing `Env#current` from crashing when Rails isn’t loaded, and new documentation for the Node package JavaScript API (`docs/node_package_api.md`). > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 81bf2b8. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
## Summary - Adds `project_root` helper that resolves the project root without requiring `Rails.root` - Falls back to `BUNDLE_GEMFILE` dirname (reliable — always set after `require "bundler/setup"`) then `Dir.pwd` - `resolve_hook_script_path` now uses `project_root` instead of hard-requiring `Rails.root` Related to #2438 — addresses the hook detection root cause (hook not running from `bin/dev` context), though the exact symptom reported in that issue (pack generation failure) could not be reproduced. ## Problem `resolve_hook_script_path` returned nil whenever `Rails.root` wasn't available (e.g., from `bin/dev` which intentionally skips loading Rails for startup speed). This caused `hook_configured?` to return false even when the precompile hook was correctly configured in `shakapacker.yml`, leading to redundant pack generation after the hook already ran. ## Companion PR This works together with [shakacode/shakapacker#963](shakacode/shakapacker#963), which fixes `Shakapacker::Env#current` to resolve the environment from `RAILS_ENV`/`RACK_ENV` env vars when Rails isn't loaded. Together, these two fixes address the `bin/dev` hook detection issue. With both fixes applied, `bin/dev` output shows the correct flow: ``` 🔧 Running Shakapacker precompile hook... Command: bin/shakapacker-precompile-hook ✅ Precompile hook completed successfully ⏭️ Skipping pack generation (handled by shakapacker precompile hook: bin/shakapacker-precompile-hook) ``` ## Supersedes #2561 PR #2561 worked around the Shakapacker `Env#current` bug by re-implementing YAML config parsing. With the Shakapacker fix in place, that workaround is no longer needed — this PR provides only the minimal `resolve_hook_script_path` fix that was still necessary. ## Test plan - [x] Verified `hook_configured?` returns `true` from non-Rails context (test app with both fixes) - [x] Verified `bin/dev` runs hook and skips redundant pack generation - [x] Verified `BUNDLE_GEMFILE` correctly resolves project root even when `Dir.pwd` differs 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Improvements** * More robust project-root detection: falls back from Rails to Gemfile directory to current working directory for clearer path resolution across environments. * Improved hook-script detection and reporting, with better handling of self-guard patterns. * **Tests** * Added tests covering project-root detection with Rails present/absent and various Gemfile scenarios. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.6 <[email protected]>
…2580) ## Summary - Reverts #2561 (squash commit 769d120), which was merged after #2568 already landed on master - #2568 + [shakacode/shakapacker#963](shakacode/shakapacker#963) fix the root cause of #2438 — #2561's YAML-parsing fallback is redundant - CHANGELOG entry updated to reference #2568 only ## What's removed All of #2561's additions on top of #2568: - `extract_precompile_hook_from_yaml` / `extract_precompile_hook_from_shakapacker_config` split - `extract_script_from_command` interpreter-prefix stripping - `extract_hash_for_environment` / `current_shakapacker_environment` helpers - `SHAKAPACKER_CONFIG_PATH` constant, `require "erb"`, `require "yaml"` - `rubocop:disable Metrics/ModuleLength` - `GENERATE_PACKS_PATTERN` expansion for `generate_packs_if_needed` - 72 lines of #2561-specific specs ## What remains (from #2568 + shakapacker#963) - `project_root` helper (Rails.root → BUNDLE_GEMFILE → Dir.pwd fallback) - `resolve_hook_script_path` using `project_root` - `require "pathname"` - 3 project_root specs - Shakapacker `Env#current` guard (separate repo, already merged) ## Why #2568 was designed to supersede #2561 — its PR description says so explicitly. Both were merged, resulting in unnecessary complexity (YAML config re-parsing, ERB evaluation, environment fallback chain) that duplicates what Shakapacker already handles after #963. ## Test plan - `bundle exec rspec react_on_rails/spec/react_on_rails/packer_utils_spec.rb` - `bundle exec rubocop react_on_rails/lib/react_on_rails/packer_utils.rb react_on_rails/spec/react_on_rails/packer_utils_spec.rb` 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved bin/dev startup reliability with enhanced hook script path resolution during early startup when Rails.root is unavailable. * Removed YAML configuration dependency, streamlining hook detection. * Added validation checks for hook script existence to prevent runtime errors. * Simplified hook script pattern matching for better clarity. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
Summary
defined?(Rails)guard toShakapacker::Env#current— falls back toRAILS_ENV/RACK_ENVenv vars, thenShakapacker::DEFAULT_ENVwhen Rails isn't loadedfallback_env_warningwhich also calledRails.envdirectlyfallback_env_warningfor logger failures without full Rails (ActiveSupport::IsolatedExecutionState not available)Related to react_on_rails#2438 — addresses the root cause of hook detection failure from
bin/devcontext.Problem
Shakapacker::Env#currentcallsRails.envdirectly with no guard:When
Shakapacker.configis accessed from a non-Rails Ruby process, this raisesNameErrorwhich gets rescued up the chain, causingEnv#inquireto silently fall back to"production"instead of resolving the correct environment.This was discovered via react_on_rails#2438 — React on Rails'
bin/devscript intentionally skips loading Rails for startup speed, then callsShakapacker.config.precompile_hookto detect hook configuration. The broken env resolution caused hook detection to fail silently.Fix
Follows the same pattern established by PR #681 for
Instance#initialize, and mirrors howRunner#initialize(line 239) already resolves the environment:Test plan
env_without_rails_spec.rb— 4 examples covering RAILS_ENV fallback, RACK_ENV fallback, development default, and no-NameError guaranteeenv_spec.rb— 4 examples still pass (Rails context unchanged)staging_env_instance_spec.rb— 2 examples still pass🤖 Generated with Claude Code
Summary by CodeRabbit
Bug Fixes
Tests