Skip to content

Shakapacker::Env#current calls Rails.env without guard, fails in non-Rails Ruby contexts #962

@ihabadham

Description

@ihabadham

Problem

Shakapacker::Env#current calls Rails.env directly with no defined?(Rails) guard:

# lib/shakapacker/env.rb
def current
  Rails.env.presence_in(available_environments)
end

When Shakapacker.config is called from a Ruby process that hasn't loaded Rails (e.g., a bin/dev script that only does require "bundler/setup"), this raises NameError: uninitialized constant Rails — which gets rescued somewhere up the chain, causing Env#inquire to silently fall back to "production" instead of resolving the correct environment.

fallback_env_warning has the same issue — it also references Rails.env directly.

How we discovered this

React on Rails' bin/dev script intentionally skips loading Rails for startup speed. It calls Shakapacker.config.precompile_hook to detect whether a precompile hook is configured. This goes through:

  1. Shakapacker.configShakapacker.instance.config
  2. Instance#config needs envInstance#envShakapacker::Env.inquire(self)
  3. Env#currentRails.envNameError

The error is rescued, current returns nil, and inquire falls back to "production". This causes the wrong environment config to be loaded (production instead of development), which can cause hook detection to fail silently.

Relationship to PR #681

PR #681 fixed a similar class of bug — Instance#initialize used Rails.root in its method signature default, which crashed in non-Rails contexts (issues #680, #736). That fix added defined?(Rails) guards to Instance and error handling to Configuration#log_fallback. But Env#current and fallback_env_warning were not in the crash path for those issues, so they were left unchanged.

The fix pattern already exists in Shakapacker

Shakapacker::Runner#initialize (line 239) already handles this correctly:

env: ENV["RAILS_ENV"] || ENV["NODE_ENV"] || "development"

The same fallback pattern should be applied to Env#current:

def current
  env = if defined?(Rails) && Rails.respond_to?(:env)
          Rails.env.to_s
        else
          ENV["RAILS_ENV"].presence || ENV["RACK_ENV"].presence
        end
  env&.presence_in(available_environments)
end

Context

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions