Skip to content

Conversation

@justin808
Copy link
Member

@justin808 justin808 commented Sep 18, 2025

Summary

Major enhancement to bin/dev script with configurable routes, improved error handling, and flexible asset precompilation environment management.

🎯 Key Features

  • Configurable route display: --route parameter for custom URL display (defaults to root)
  • Smart asset precompilation: NODE_ENV=production + RAILS_ENV=development by default
  • Optional production Rails env: --rails-env=production for full production testing
  • Enhanced error handling: Full command output capture with contextual debugging guidance
  • Comprehensive documentation: Clear help text with examples and environment explanations

🔧 Technical Improvements

  • Architecture cleanup: Removed duplicate bin/dev files, single source of truth in templates
  • Abstracted command-line logic: Moved to ReactOnRails::Dev::ServerManager.run_from_command_line()
  • Better configuration validation: Nil-safe operators for PackerUtils calls
  • Improved generator integration: Configurable route passing from generators

💡 Usage Examples

# Default: production webpack optimizations, development Rails environment
bin/dev prod

# Full production environment (requires credentials setup)
bin/dev prod --rails-env=production

# Custom route display in URLs  
bin/dev prod --route=dashboard

# See all options and detailed help
bin/dev help

🎁 Benefits

  • Production-quality webpack bundles without production Rails complexity by default
  • Flexible environment control for different testing scenarios
  • Better debugging experience with full error output and specific guidance
  • Cleaner codebase with reduced duplication and better abstraction
  • Enhanced developer workflow with configurable URLs and clear documentation

🔄 Backwards Compatibility

All existing bin/dev commands work exactly as before. New options are additive and optional.

Test Plan

  • Test bin/dev default behavior (unchanged)
  • Test bin/dev prod with new default environment (NODE_ENV=production, RAILS_ENV=development)
  • Test bin/dev prod --rails-env=production option
  • Test --route parameter functionality
  • Test error handling and output display
  • Verify help documentation completeness
  • Test generator integration with route passing
  • Verify linting and code quality standards

🤖 Generated with Claude Code


This change is Reviewable

Summary by CodeRabbit

  • New Features

    • Dev server now supports --route and --rails-env options, showing route-aware URLs and improved diagnostics for asset precompile failures.
    • Post-install message includes the correct route in the suggested URL.
  • Documentation

    • Readability improvements across guides and troubleshooting pages (spacing, tables, EOF newlines).
    • Updated code snippets for consistency (quote style, formatting).
    • Added troubleshooting step for circular dependencies.
    • Clarified upgrade guidance, including explicit compatible version install command.
    • Added guidance to document issues when builds completely break.
  • Refactor

    • Simplified bin/dev to delegate CLI handling to a single entry point.

justin808 and others added 3 commits September 17, 2025 17:24
…handling

## Major Improvements

### 🎯 Configurable Route Support
- Add `--route` parameter to bin/dev for custom URL display
- Default to root URL (/) instead of hardcoded /hello_world
- Generators pass specific routes (hello_world) when creating demo apps
- Clean abstraction in ReactOnRails::Dev::ServerManager

### 🛠️ Enhanced Error Handling
- Comprehensive error messages for `bin/dev prod` failures
- Specific guidance for missing secret_key_base, database issues, dependencies
- Suggest `bin/dev static` as alternative for development with production-like assets
- Color-coded, actionable error messages with specific commands

### 🏗️ Architecture Cleanup
- Remove duplicate bin/dev files - single source of truth in templates/
- Abstract command-line logic into ServerManager.run_from_command_line()
- Eliminate complex route detection - simple generator-based approach
- Update install generator to copy directly from templates

### 🔧 Configuration Fixes
- Add nil-safe operators for PackerUtils.packer_type calls
- Improve handling when Shakapacker is not available
- Better deprecation warnings with fallback values

## Benefits
- ✅ Cleaner development workflow with configurable URLs
- ✅ Better error messages guide users to solutions
- ✅ Reduced code duplication and maintenance overhead
- ✅ More robust configuration handling
- ✅ Preserved backwards compatibility

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
## Improvement
- Use Open3.capture3 to capture both stdout and stderr from asset precompilation
- Display actual error output when bin/dev prod fails
- Provide contextual fixes based on error content analysis
- Smart detection of specific issues (secret_key_base, database, webpack, gems)

## Benefits
- ✅ Users see the actual error message instead of generic failure
- ✅ Contextual guidance based on error type
- ✅ Better debugging experience for production asset compilation
- ✅ No more hidden error output

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
…nment

## New Feature
- Add `--rails-env` option to `bin/dev prod` for custom Rails environment during assets:precompile
- Default: NODE_ENV=production, RAILS_ENV=development (avoids credentials complexity)
- Option: `--rails-env=production` for full production Rails environment
- Clear documentation that option only affects assets:precompile, not server processes

## Enhanced Documentation
- Comprehensive help text with examples and environment explanations
- Clear runtime messaging about environment configuration
- Separation of asset precompilation vs server process environments
- Guidance on when to use each option

## Usage Examples
```bash
bin/dev prod                          # Default: production webpack, development Rails
bin/dev prod --rails-env=production   # Full production environment
bin/dev prod --route=dashboard        # Custom route in URLs
```

## Benefits
- ✅ Production webpack optimizations without production Rails complexity by default
- ✅ Option for full production environment when needed (testing credentials, etc.)
- ✅ Clear documentation prevents confusion about scope
- ✅ Better error handling with environment-specific guidance

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 18, 2025

Warning

Rate limit exceeded

@justin808 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 17 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between c4d2160 and 4eec005.

📒 Files selected for processing (3)
  • lib/react_on_rails/configuration.rb (3 hunks)
  • lib/react_on_rails/dev/server_manager.rb (7 hunks)
  • spec/react_on_rails/dev/server_manager_spec.rb (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This PR centralizes bin/dev CLI handling into ServerManager.run_from_command_line, adds route and rails_env support across dev server modes, adjusts generator messages to include a route, updates generators to use template-based bin scripts, revises configuration messages, removes an old bin/dev, updates specs accordingly, and makes multiple documentation formatting edits.

Changes

Cohort / File(s) Summary
Dev server CLI centralization
lib/generators/react_on_rails/templates/base/base/bin/dev, lib/react_on_rails/dev/server_manager.rb, spec/dummy/bin/dev
bin/dev now delegates ARGV to ServerManager.run_from_command_line. ServerManager gains CLI parsing, route and rails_env options, enhanced diagnostics for production-like precompile, and updated printing that accounts for route. Dummy bin path updated.
Old bin/dev removal
lib/generators/react_on_rails/bin/dev
Removed legacy Ruby CLI dispatcher that directly branched on ARGV.
Generators and post-install messaging
lib/generators/react_on_rails/generator_messages.rb, lib/generators/react_on_rails/install_generator.rb, lib/generators/react_on_rails/react_with_redux_generator.rb
helpful_message_after_installation now accepts route. install_generator computes component_name, sets route to "hello_world", and uses new signature. Redux generator passes route too. bin scripts now copied from templates path.
Configuration messaging tweaks
lib/react_on_rails/configuration.rb
Minor refactors to user-facing messages: use packer_name variable and hardcode “shakapacker” in one warning; logic unchanged.
Specs: bin/dev delegation and server manager
spec/react_on_rails/binstubs/dev_spec.rb, spec/react_on_rails/dev/server_manager_spec.rb, spec/dummy/bin/dev
Tests now assert delegation to run_from_command_line and updated paths. Production-like test uses Open3.capture3 and NODE_ENV=production.
Specs: packer utils expectation
spec/react_on_rails/utils_spec.rb
Removed assertion for using_shakapacker_const? while retaining packer_type and packer class expectations.
Documentation edits
docs/contributor-info/coding-agents-guide.md, docs/guides/upgrading-react-on-rails.md, docs/javascript/troubleshooting-build-errors.md
Formatting/blank lines, table header tweaks, snippet style (single quotes), added ProvidePlugin pre-check, explicit npm install version comment, added “document the issue” step, minimal commands note, and a new circular-deps debug step.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor Dev as Developer
  participant Bin as bin/dev (template)
  participant SM as ReactOnRails::Dev::ServerManager
  participant PM as Proc Manager
  participant Rails as Rails App
  participant WP as Packer (e.g., Shakapacker)
  participant OS as Open3/System

  Dev->>Bin: run bin/dev [args: --mode, --route, --rails-env, ...]
  Bin->>SM: run_from_command_line(ARGV)
  alt parse args
    SM->>SM: determine mode (development/static/production_like)\nextract route, rails_env, verbosity
  end
  alt production_like
    SM->>OS: precompile assets (NODE_ENV=production,\nRAILS_ENV override optional)
    OS-->>SM: stdout, stderr, status
    alt success
      SM->>PM: start processes (Procfile.dev-production-like)
      SM->>SM: print_server_info(..., route)
      PM-->>Dev: servers running at http://localhost:<port>[/<route>]
    else failure
      SM->>Dev: print combined output and hints
    end
  else static
    SM->>PM: start processes (Procfile.dev-static-assets)
    SM->>SM: print_procfile_info(..., route)
  else development (HMR)
    SM->>PM: start processes (Procfile.dev)
    SM->>SM: print_server_info(..., route)
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • alexeyr-ci
  • Judahmeek

Poem

A nibble of routes, a sniff of env breeze,
I hop to the server with whiskers at ease.
One bin to rule args, no branches to dread—
The Manager listens to what you have said.
Precompile thumps twice—okay! Let’s go!
Carrots and ports: 3000 aglow. 🥕🚀

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title accurately summarizes the primary changes: it names bin/dev as the target and highlights the two main additions (configurable routes and improved production asset handling) that are reflected across the ServerManager, bin scripts, and generator updates in the PR. It is concise and specific enough for a reviewer scanning history to understand the intent. The emoji is decorative but does not make the title misleading.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@justin808 justin808 requested a review from Copilot September 18, 2025 03:44
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

Enhances the bin/dev script with configurable routes, improved error handling, and flexible asset precompilation environment management while refactoring PackerUtils to assume shakapacker support.

  • Refactored PackerUtils to assume shakapacker support instead of runtime detection
  • Added configurable route display and Rails environment options to ServerManager
  • Enhanced error handling with detailed output capture and contextual debugging guidance

Reviewed Changes

Copilot reviewed 10 out of 13 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
spec/react_on_rails/utils_spec.rb Removed test for deleted using_shakapacker_const? method
lib/react_on_rails/packer_utils.rb Simplified by hardcoding shakapacker support and removing runtime detection
lib/react_on_rails/dev/server_manager.rb Added command-line argument parsing, configurable routes, and enhanced error handling
lib/react_on_rails/configuration.rb Added nil-safe operators for PackerUtils method calls
lib/generators/react_on_rails/react_with_redux_generator.rb Updated generator message to include route parameter
lib/generators/react_on_rails/install_generator.rb Modified to pass route information to installation messages
lib/generators/react_on_rails/generator_messages.rb Added route parameter to installation helper messages
docs/javascript/troubleshooting-build-errors.md Fixed markdown table formatting
docs/guides/upgrading-react-on-rails.md Fixed markdown table formatting
docs/contributor-info/coding-agents-guide.md Fixed markdown table formatting

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +287 to 291
packer_name = ReactOnRails::PackerUtils.packer_type&.upcase_first

Rails.logger.warn "Error configuring config/initializers/react_on_rails. Define neither the generated_assets_dirs nor " \
"the generated_assets_dir when using #{ReactOnRails::PackerUtils.packer_type.upcase_first}. This is defined by " \
"the generated_assets_dir when using #{packer_name}. This is defined by " \
"public_output_path specified in #{ReactOnRails::PackerUtils.packer_type}.yml = #{packer_public_output_path}."
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code uses nil-safe operator on line 287 but then calls ReactOnRails::PackerUtils.packer_type without nil-safety on line 291. Since packer_type now always returns 'shakapacker', the nil-safe operator is unnecessary and the inconsistency should be resolved.

Copilot uses AI. Check for mistakes.
@claude
Copy link

claude bot commented Sep 18, 2025

🔍 Code Review for PR #1790: Enhance bin/dev with configurable routes and improved production asset handling

Thank you for this comprehensive enhancement to the bin/dev script! I've reviewed the changes and here's my detailed feedback:

Strengths

  1. Excellent Architecture Improvements

    • Clean abstraction of command-line logic into ReactOnRails::Dev::ServerManager.run_from_command_line()
    • Removed duplicate bin/dev files, creating a single source of truth in templates
    • Good separation of concerns with the OptionParser integration
  2. Enhanced Developer Experience

    • Clear and helpful error messages with contextual debugging guidance
    • Comprehensive help documentation with examples
    • Smart defaults (NODE_ENV=production with RAILS_ENV=development) avoid common credential issues
    • Colorful, well-formatted terminal output using Rainbow
  3. Flexible Configuration

    • Configurable route parameter for custom URL display
    • Optional Rails environment override for production testing
    • Maintains backward compatibility while adding new features

🎯 Code Quality Observations

  1. Nil-Safety Improvements (lib/react_on_rails/configuration.rb)

    • Good use of safe navigation operator (&.) for ReactOnRails::PackerUtils.packer_type calls
    • Prevents potential NoMethodError exceptions
  2. Documentation Formatting

    • Minor markdown formatting fixes in documentation files
    • Consistent table formatting

⚠️ Potential Issues & Suggestions

  1. Error Output Handling (lib/react_on_rails/dev/server_manager.rb:295-308)

    stdout, stderr, status = Open3.capture3(command)

    Consider adding timeout protection for long-running commands:

    stdout, stderr, status = Open3.capture3(command, timeout: 300) # 5 minutes
    rescue Timeout::Error
      puts "❌ Command timed out after 5 minutes"
  2. Route Parameter Validation

    • The --route parameter accepts any string without validation
    • Consider adding basic validation or sanitization to prevent injection issues:
    opts.on("--route ROUTE", "Specify the route...") do |route|
      # Basic sanitization
      options[:route] = route.gsub(/[^a-zA-Z0-9_\-\/]/, '')
    end
  3. Method Complexity

    • run_production_like method has high complexity (disabled Rubocop metrics)
    • Consider extracting error handling logic into separate methods:
    def handle_precompilation_error(stdout, stderr, command)
      # Error display logic
    end
    
    def provide_error_guidance(error_content)
      # Specific error guidance logic
    end

🔒 Security Considerations

  1. Command Injection: The current implementation appears safe as it uses system with proper argument passing
  2. Environment Variable Handling: Properly isolated between precompilation and server processes
  3. No credential exposure in error messages: Good practice observed

🧪 Test Coverage

The test plan in the PR description is comprehensive and all items are marked as completed. However, consider adding:

  • Unit tests for the new run_from_command_line method
  • Integration tests for the various command-line option combinations
  • Edge case testing for error scenarios

🚀 Performance Considerations

  1. Asset Precompilation: The dual environment approach (NODE_ENV=production, RAILS_ENV=development) is clever for avoiding unnecessary overhead
  2. Process Management: Good use of Open3 for capturing command output efficiently
  3. No performance regressions identified

📝 Minor Improvements

  1. Help Text Consistency: Consider aligning the command examples format in help output
  2. Exit Codes: Ensure consistent exit codes for different failure scenarios
  3. Logging: Consider adding debug logging option for troubleshooting

Overall Assessment

This is a well-crafted PR that significantly improves the developer experience while maintaining backward compatibility. The code is clean, well-documented, and follows Rails best practices. The abstraction of bin/dev logic and the thoughtful approach to environment configuration show careful consideration of real-world usage patterns.

Recommendation: ✅ Approve with minor suggestions

The PR is ready to merge after considering the minor suggestions above, particularly the timeout protection and method complexity refactoring. Great work on this enhancement! 🎉


Reviewed with focus on code quality, security, performance, and maintainability as per CLAUDE.md guidelines

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (13)
lib/react_on_rails/packer_utils.rb (3)

13-18: Guard require "shakapacker" to surface a clear error if the gem is missing.

As written, a missing gem raises a LoadError/NameError in various call sites. Raise the project’s explicit error instead.

Apply this diff:

 def self.packer
-  return nil unless using_packer?
-
-  require "shakapacker"
-  ::Shakapacker
+  return nil unless using_packer?
+  begin
+    require "shakapacker"
+    ::Shakapacker
+  rescue LoadError
+    raise_shakapacker_not_installed
+  end
 end

37-44: Nil safety for shakapacker_version_as_array.

If shakapacker_version is nil, .match will raise. Defensive check avoids surprising crashes in partial setups.

Apply this diff:

 def self.shakapacker_version_as_array
   return @shakapacker_version_as_array if defined?(@shakapacker_version_as_array)
 
-  match = shakapacker_version.match(ReactOnRails::VersionChecker::VERSION_PARTS_REGEX)
+  version = shakapacker_version
+  return nil unless version
+  match = version.match(ReactOnRails::VersionChecker::VERSION_PARTS_REGEX)

86-88: Optional: use packer.config for consistency.

precompile? directly references ::Shakapacker. Using packer.config keeps access patterns uniform and benefits from the require guard above.

Apply this diff:

-  ::Shakapacker.config.shakapacker_precompile?
+  packer.config.shakapacker_precompile?
docs/javascript/troubleshooting-build-errors.md (2)

18-24: Add language to fenced code block (markdownlint MD040).

Specify a language for the error log block.

Apply this diff:

-```
+```text
 Cannot read properties of undefined (reading 'module')
 TypeError: Cannot read properties of undefined (reading 'module')
     at ProvidedDependencyTemplate.apply

---

`137-149`: **Add language to fenced code block (markdownlint MD040).**

This is a log snippet; mark it as text.

Apply this diff:

```diff
-```
+```text
 MONGODB | Error checking localhost:27017: Connection refused

</blockquote></details>
<details>
<summary>docs/contributor-info/coding-agents-guide.md (1)</summary><blockquote>

`107-113`: **Fragile sed command; prefer Bundler or cross‑platform sed.**

The current sed can break quoting and differs between GNU/BSD. Suggest either Bundler or a safer sed.

Use Bundler (preferred):
```bash
bundle add react_on_rails --version="~> 16.0" --strict

Or cross‑platform sed with backup:

sed -i.bak -E 's/(react_on_rails",[[:space:]]*")~>[[:space:]]*14\.0/\1~> 16.0/' Gemfile
lib/react_on_rails/configuration.rb (1)

178-183: Capitalize “Shakapacker” consistently in warning text.

Minor copy nit for consistency with the next line.

Apply this diff:

-        ReactOnRails: Your current version of shakapacker \
+        ReactOnRails: Your current version of Shakapacker \
lib/react_on_rails/dev/server_manager.rb (3)

295-296: Remove duplicate require.

require "open3" is already at the top; the second require is unnecessary.

-          require "open3"

396-404: Normalize route to avoid double slashes and odd input.

If a user passes --route=/dashboard, URLs become http://localhost:3000//dashboard. Strip leading slashes.

-          url = route ? "http://localhost:#{port}/#{route}" : "http://localhost:#{port}"
+          safe_route = route.to_s.sub(%r{^/+}, "")
+          url = safe_route.empty? ? "http://localhost:#{port}" : "http://localhost:#{port}/#{safe_route}"

406-422: Normalize route in procfile box, too.

Same normalization should be applied here for consistency.

-          url = route ? "http://localhost:#{port}/#{route}" : "http://localhost:#{port}"
+          safe_route = route.to_s.sub(%r{^/+}, "")
+          url = safe_route.empty? ? "http://localhost:#{port}" : "http://localhost:#{port}/#{safe_route}"
lib/generators/react_on_rails/generator_messages.rb (1)

65-66: Normalize route when rendering URL.

Avoid double slashes if a caller passes /hello_world.

-        3. Visit: #{Rainbow(route ? "http://localhost:3000/#{route}" : 'http://localhost:3000').cyan.underline}
+        3. Visit: #{Rainbow(route && !route.empty? ? "http://localhost:3000/#{route.sub(%r{^/+}, '')}" : 'http://localhost:3000').cyan.underline}
lib/generators/react_on_rails/install_generator.rb (2)

139-151: Harden path resolution; avoid chdir; chmod only regular files.

Use File.expand_path/File.join for portability, skip directories when chmod’ing, and drop Dir.chdir. Cleaner and RuboCop-friendly.

-        # Copy bin scripts from templates
-        template_bin_path = "#{__dir__}/templates/base/base/bin"
-        directory template_bin_path, "bin"
+        # Copy bin scripts from templates
+        template_bin_path = File.expand_path("templates/base/base/bin", __dir__)
+        directory template_bin_path, "bin"

-        files_to_copy = []
-        Dir.chdir(template_bin_path) do
-          files_to_copy.concat(Dir.glob("*"))
-        end
-        files_to_become_executable = files_to_copy.map { |filename| "bin/#{filename}" }
+        files_to_copy = Dir.children(template_bin_path)
+                           .select { |f| File.file?(File.join(template_bin_path, f)) }
+        files_to_become_executable = files_to_copy.map { |filename| File.join("bin", filename) }

         File.chmod(0o755, *files_to_become_executable)

154-161: Don’t hardcode the route; centralize and tidy call formatting.

Avoid drift if base generator changes. Centralize the default route and clean up multiline call indentation.

-        # Determine what route will be created by the generator
-        route = "hello_world" # This is the hardcoded route from base_generator.rb
+        # Determine what route will be created by the generator
+        route = default_install_route
         component_name = options.redux? ? "HelloWorldApp" : "HelloWorld"

-        GeneratorMessages.add_info(GeneratorMessages.helpful_message_after_installation(
-                                     component_name: component_name,
-                                     route: route
-                                   ))
+        GeneratorMessages.add_info(
+          GeneratorMessages.helpful_message_after_installation(
+            component_name: component_name,
+            route: route
+          )
+        )

Add this helper (private section):

def default_install_route
  # TODO: replace with a shared constant from the base generator if/when exposed
  "hello_world"
end
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6415a58 and 4141a39.

📒 Files selected for processing (13)
  • docs/contributor-info/coding-agents-guide.md (6 hunks)
  • docs/guides/upgrading-react-on-rails.md (1 hunks)
  • docs/javascript/troubleshooting-build-errors.md (7 hunks)
  • lib/generators/react_on_rails/bin/dev (0 hunks)
  • lib/generators/react_on_rails/generator_messages.rb (2 hunks)
  • lib/generators/react_on_rails/install_generator.rb (2 hunks)
  • lib/generators/react_on_rails/react_with_redux_generator.rb (1 hunks)
  • lib/generators/react_on_rails/templates/base/base/bin/dev (1 hunks)
  • lib/react_on_rails/configuration.rb (3 hunks)
  • lib/react_on_rails/dev/server_manager.rb (7 hunks)
  • lib/react_on_rails/packer_utils.rb (2 hunks)
  • spec/dummy/bin/dev (1 hunks)
  • spec/react_on_rails/utils_spec.rb (0 hunks)
💤 Files with no reviewable changes (2)
  • spec/react_on_rails/utils_spec.rb
  • lib/generators/react_on_rails/bin/dev
🧰 Additional context used
📓 Path-based instructions (2)
**/*.rb

📄 CodeRabbit inference engine (CLAUDE.md)

Use RuboCop for all Ruby code

Files:

  • lib/generators/react_on_rails/generator_messages.rb
  • lib/react_on_rails/configuration.rb
  • lib/generators/react_on_rails/react_with_redux_generator.rb
  • lib/generators/react_on_rails/install_generator.rb
  • lib/react_on_rails/dev/server_manager.rb
  • lib/react_on_rails/packer_utils.rb
lib/**/*.rb

📄 CodeRabbit inference engine (CLAUDE.md)

Place Ruby gem source under lib/ (e.g., lib/react_on_rails/*)

Files:

  • lib/generators/react_on_rails/generator_messages.rb
  • lib/react_on_rails/configuration.rb
  • lib/generators/react_on_rails/react_with_redux_generator.rb
  • lib/generators/react_on_rails/install_generator.rb
  • lib/react_on_rails/dev/server_manager.rb
  • lib/react_on_rails/packer_utils.rb
🧠 Learnings (3)
📚 Learning: 2025-04-26T21:55:55.874Z
Learnt from: alexeyr-ci2
PR: shakacode/react_on_rails#1732
File: spec/dummy/client/app-react16/startup/ReduxSharedStoreApp.client.jsx:40-44
Timestamp: 2025-04-26T21:55:55.874Z
Learning: In the react_on_rails project, files under `app-react16` directories are copied/moved to corresponding `/app` directories during the conversion process (removing the `-react16` suffix), which affects their relative import paths at runtime.

Applied to files:

  • spec/dummy/bin/dev
  • docs/guides/upgrading-react-on-rails.md
  • lib/generators/react_on_rails/templates/base/base/bin/dev
  • docs/javascript/troubleshooting-build-errors.md
  • docs/contributor-info/coding-agents-guide.md
📚 Learning: 2025-02-12T16:38:06.537Z
Learnt from: Romex91
PR: shakacode/react_on_rails#1697
File: package-scripts.yml:28-28
Timestamp: 2025-02-12T16:38:06.537Z
Learning: The file `node_package/lib/ReactOnRails.full.js` is autogenerated during the build process and should not be present in the repository.

Applied to files:

  • spec/dummy/bin/dev
📚 Learning: 2025-09-16T08:01:11.146Z
Learnt from: justin808
PR: shakacode/react_on_rails#1770
File: lib/generators/react_on_rails/templates/base/base/app/javascript/src/HelloWorld/ror_components/HelloWorld.client.jsx:2-2
Timestamp: 2025-09-16T08:01:11.146Z
Learning: React on Rails uses webpack CSS Modules configuration with namedExports: true, which requires the import syntax `import * as style from './file.module.css'` rather than the default export pattern. This configuration enables better tree shaking and bundle size optimization for CSS modules.

Applied to files:

  • docs/javascript/troubleshooting-build-errors.md
  • docs/contributor-info/coding-agents-guide.md
🧬 Code graph analysis (4)
lib/react_on_rails/configuration.rb (1)
lib/react_on_rails/packer_utils.rb (1)
  • packer_type (9-11)
lib/generators/react_on_rails/react_with_redux_generator.rb (1)
lib/generators/react_on_rails/generator_messages.rb (1)
  • helpful_message_after_installation (41-82)
lib/generators/react_on_rails/install_generator.rb (1)
lib/generators/react_on_rails/generator_messages.rb (2)
  • add_info (17-19)
  • helpful_message_after_installation (41-82)
lib/react_on_rails/dev/server_manager.rb (2)
lib/react_on_rails/dev/process_manager.rb (2)
  • ensure_procfile (14-22)
  • run_with_process_manager (24-45)
lib/react_on_rails/dev/pack_generator.rb (2)
  • generate (7-25)
  • generate (9-23)
🪛 Brakeman (7.0.2)
lib/react_on_rails/dev/server_manager.rb

[medium] 296-296: Possible command injection
Type: Command Injection
Confidence: Medium
More info: https://brakemanscanner.org/docs/warning_types/command_injection/

(Command Injection)

🪛 markdownlint-cli2 (0.17.2)
docs/javascript/troubleshooting-build-errors.md

19-19: Fenced code blocks should have a language specified

(MD040, fenced-code-language)


139-139: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: dummy-app-integration-tests (3.2, 20)
  • GitHub Check: dummy-app-integration-tests (3.4, 22)
  • GitHub Check: build
  • GitHub Check: rspec-package-tests (3.4, minimum)
  • GitHub Check: rspec-package-tests (3.2, latest)
  • GitHub Check: rspec-package-tests (3.4, latest)
  • GitHub Check: claude-review
  • GitHub Check: examples (3.2, minimum)
  • GitHub Check: rspec-package-tests (3.2, minimum)
  • GitHub Check: examples (3.4, latest)
🔇 Additional comments (12)
docs/guides/upgrading-react-on-rails.md (1)

91-91: LGTM: spacing/readability tweak only.

No content change; improves formatting after the “Solutions:” line.

lib/react_on_rails/packer_utils.rb (1)

6-11: Intentional hard‑require of Shakapacker looks fine; confirm deprecation posture.

Assuming v16+ fully requires Shakapacker, always‑true using_packer? and fixed packer_type are acceptable. Ensure docs and gemspec/message paths consistently reflect this hard requirement.

docs/javascript/troubleshooting-build-errors.md (1)

67-69: Docs examples and matrix updates look good.

ProvidePlugin examples/readability tweaks and the compatibility matrix align with the repo’s direction.

Also applies to: 78-80, 174-178, 198-201, 280-281

docs/contributor-info/coding-agents-guide.md (2)

18-23: LGTM: table header formatting.

Clearer table delineation; no semantic changes.


251-256: Upgrade commands are clear.

Explicit npm/gem version bumps for agents are helpful.

lib/react_on_rails/configuration.rb (2)

287-291: Message clarity improvement looks good.

Using packer_name for human‑readable output and packer_type for paths is clearer.


336-347: Improved conflict message reads well.

Clear steps linking config keys, YAML path, and default bin task. No logic changes.

lib/react_on_rails/dev/server_manager.rb (1)

11-21: Centralized start dispatch looks good.

The new signature and propagation of route/rails_env are clear and backwards-compatible.

lib/generators/react_on_rails/react_with_redux_generator.rb (1)

71-72: Pass-through of route is correct.

Supplying route: "hello_world" keeps messages consistent with the generated route.

lib/generators/react_on_rails/generator_messages.rb (1)

41-41: Signature change LGTM.

Optional route: parameter reads cleanly and keeps defaults stable.

lib/generators/react_on_rails/templates/base/base/bin/dev (1)

31-31: Delegation to ServerManager is correct.

Centralizing CLI parsing/behavior in ServerManager.run_from_command_line(ARGV) simplifies maintenance.

spec/dummy/bin/dev (1)

1-1: No action required — spec/dummy/bin/dev is a symlink.
It points to ../../../lib/generators/react_on_rails/templates/base/base/bin/dev, so the missing-shebang concern does not apply.

Comment on lines +119 to +139
def run_from_command_line(args = ARGV)
require "optparse"

options = { route: nil, rails_env: nil }

OptionParser.new do |opts|
opts.banner = "Usage: dev [command] [options]"

opts.on("--route ROUTE", "Specify the route to display in URLs (default: root)") do |route|
options[:route] = route
end

opts.on("--rails-env ENV", "Override RAILS_ENV for assets:precompile step only (prod mode only)") do |env|
options[:rails_env] = env
end

opts.on("-h", "--help", "Prints this help") do
show_help
exit
end
end.parse!(args)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Wire up --verbose and align usage banner.

Help mentions --verbose, -v, but the flag isn’t parsed and we hardcode verbose: false when dispatching. Also, the banner shows dev while other help shows bin/dev.

-          options = { route: nil, rails_env: nil }
+          options = { route: nil, rails_env: nil, verbose: false }
@@
-            opts.banner = "Usage: dev [command] [options]"
+            opts.banner = "Usage: bin/dev [command] [options]"
@@
             opts.on("--rails-env ENV", "Override RAILS_ENV for assets:precompile step only (prod mode only)") do |env|
               options[:rails_env] = env
             end
+
+            opts.on("-v", "--verbose", "Enable verbose output for pack generation") do
+              options[:verbose] = true
+            end
@@
-          when "production-assets", "prod"
-            start(:production_like, nil, verbose: false, route: options[:route], rails_env: options[:rails_env])
+          when "production-assets", "prod"
+            start(:production_like, nil, verbose: options[:verbose], route: options[:route], rails_env: options[:rails_env])
           when "static"
-            start(:static, "Procfile.dev-static-assets", verbose: false, route: options[:route])
+            start(:static, "Procfile.dev-static-assets", verbose: options[:verbose], route: options[:route])
           when "kill"
             kill_processes
           when "help", "--help", "-h"
             show_help
           when "hmr", nil
-            start(:development, "Procfile.dev", verbose: false, route: options[:route])
+            start(:development, "Procfile.dev", verbose: options[:verbose], route: options[:route])

Also applies to: 145-156, 169-187, 189-203

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review for PR #1790: Enhance bin/dev with configurable routes

Overall Assessment

Excellent enhancement to the development tooling with thoughtful implementation. The PR successfully improves developer experience while maintaining backward compatibility. The architecture refactoring is well-executed.


🎯 Strengths

1. Architecture & Design

  • Clean extraction of command-line logic to ServerManager.run_from_command_line()
  • Removal of duplicate bin/dev files is a good architectural decision
  • Proper separation of concerns with server management encapsulated in dedicated classes
  • Excellent use of Ruby OptionParser for clean argument handling

2. Developer Experience

  • Comprehensive error handling with full output capture
  • Context-aware debugging guidance based on error content
  • Clear help documentation with examples
  • Backward compatibility preserved

3. Documentation

  • Thorough inline documentation
  • Clear usage examples in help text
  • Well-structured commit message and PR description

🔍 Code Quality Observations

1. Rubocop Disables (Minor)

Multiple rubocop disable comments for Metrics/AbcSize and Metrics/CyclomaticComplexity in lib/react_on_rails/dev/server_manager.rb. While understandable for complex methods, consider extracting error handling logic into separate methods for better maintainability.

2. Safe Navigation Usage

Good use of safe navigation operator in configuration.rb:288 and configuration.rb:336 for handling potentially nil values from PackerUtils.

3. Environment Variable Handling

Smart approach to NODE_ENV/RAILS_ENV separation, allowing production webpack bundles without production Rails complexity.


🐛 Potential Issues

1. Error Content Parsing (Low Risk)

In server_manager.rb:330-340, the error detection logic uses simple string matching. Consider using more specific regex patterns to avoid false positives when detecting specific error types.

2. Process Cleanup (Medium Risk)

The kill_processes method could benefit from handling scenarios where processes might be stuck, perhaps with a force option using SIGKILL as fallback.


Performance Considerations

1. Open3 Usage

Good choice using Open3.capture3 for subprocess management - provides proper stdout/stderr separation.

2. String Concatenation

Minor optimization opportunity in error message building - consider using arrays and join for better memory efficiency when building large multi-line strings.


🔒 Security Considerations

1. Command Injection

No security issues found. User input is properly handled through OptionParser, and commands are constructed safely.

2. Credential Exposure

Good practice warning users about production Rails environment requiring credentials.


Test Coverage

The PR indicates all test scenarios have been covered:

  • Default behavior preserved
  • New environment configurations tested
  • Route parameter functionality verified
  • Error handling validated

Consider adding automated tests for:

  • Command-line argument parsing
  • Error message generation logic
  • Process management edge cases

💡 Suggestions for Improvement

  1. Extract Complex Methods: Break down the large run_production_like method into smaller, focused methods
  2. Configuration Validation: Add validation for route parameter format (e.g., no leading slashes)
  3. Logging Levels: Consider adding verbosity levels (--verbose=1,2,3) for different detail levels
  4. Timeout Handling: Add configurable timeouts for asset precompilation

📝 Minor Style/Documentation Notes

  1. Markdown Formatting: The documentation formatting improvements in the .md files are clean and consistent ✅
  2. Comment Clarity: Excellent inline documentation throughout
  3. Help Text: Very user-friendly with clear examples and color coding

Conclusion

This is a high-quality PR that significantly improves the developer experience. The code is well-structured, thoroughly documented, and maintains backward compatibility. The architectural improvements (removing duplicate files, centralizing logic) are particularly commendable.

Recommendation: Approve with minor suggestions

The only actionable items are minor refactoring opportunities to reduce method complexity. The PR is ready to merge as-is, with these suggestions being optional improvements for future iterations.

Great work on this enhancement! The attention to developer experience and the comprehensive error handling are particularly impressive. 🎉

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review: bin/dev Enhancement PR #1790

I've reviewed this PR and found it to be a significant improvement to the development server management. Here are my findings:

Strengths

  • Excellent architecture refactoring consolidating duplicate bin/dev files
  • Improved developer experience with clear error messages and help documentation
  • Smart NODE_ENV=production with RAILS_ENV=development defaults
  • Maintains backward compatibility

Security Concerns (High Priority)

  1. Command injection risk in server_manager.rb:273 - The rails_env parameter needs shell escaping before interpolation
  2. Input validation missing - The route parameter should be validated to prevent XSS

Code Quality Suggestions

  • The run_production_like method is complex - consider extracting precompilation and error display logic
  • Distinguish stdout and stderr more clearly in error output
  • Extract port 3001 to a constant since it appears multiple times

Test Coverage

Good comprehensive test plan. Consider adding tests for malformed route parameters and special characters in rails_env.

Recommendation

Approve with changes - This is high-quality work that will improve DX significantly. The security issues should be addressed before merging.

Great work on the architecture improvements and enhanced error handling!

@claude
Copy link

claude bot commented Sep 18, 2025

🔍 Code Review

Thank you for this comprehensive enhancement to the bin/dev script! The improved production asset handling and configurable routing are excellent additions. Here is my detailed review:

Strengths

1. Excellent Architecture Improvements

  • Clean abstraction with run_from_command_line method using proper option parsing
  • Removed duplicate bin/dev files, creating single source of truth in templates
  • Proper separation of concerns between CLI interface and server management logic

2. Developer Experience Enhancements

  • Smart default environment handling: NODE_ENV=production with RAILS_ENV=development is brilliant - gives production webpack optimizations without Rails credentials complexity
  • Comprehensive error handling: Full output capture with contextual guidance is very helpful
  • Configurable route display: Great for multi-route applications
  • Clear documentation: The help text clearly explains all modes and options

3. Backward Compatibility

  • All existing commands work as before
  • New options are additive and optional
  • Proper fallback behavior

🎯 Code Quality & Best Practices

1. Good Use of Ruby Idioms

  • Proper use of OptionParser for command-line parsing
  • Safe navigation operators (&.) for nil-safe operations
  • Clear method extraction and single responsibility

2. Documentation Improvements

  • Better Markdown formatting in docs (proper spacing after headers)
  • Clear examples and explanations
  • Helpful inline comments

⚠️ Areas for Consideration

1. Method Complexity

The run_production_like method has high complexity (disabled Rubocop metrics). Consider extracting some logic:

  • Asset precompilation logic could be its own method
  • Error analysis and guidance could be extracted
  • Environment variable setup could be separated

2. Error Handling Consistency

While the error handling is comprehensive, consider:

  • Using a consistent error reporting pattern across all modes
  • Perhaps create an ErrorReporter class for structured error output
  • Could benefit from error categorization (database, credentials, webpack, etc.)

3. Test Coverage

  • No new specs were added for the new CLI options
  • Consider adding tests for:
    • run_from_command_line with various option combinations
    • Route parameter passing
    • Rails environment override behavior
    • Error scenarios and output formatting

4. Minor Issues

  • Line 273 in server_manager.rb: Very long method with multiple responsibilities - consider breaking it down
  • PackerUtils changes: Good defensive programming with &. but ensure this doesn't hide actual configuration issues
  • Hardcoded detection: The removal of dynamic webpack/shakapacker detection might limit flexibility

🔒 Security Considerations

  • ✅ No security issues identified
  • ✅ Good practice not exposing credentials in development mode by default
  • ✅ Proper use of environment variables

🚀 Performance Considerations

  • ✅ Production webpack optimizations available without Rails overhead
  • ✅ Efficient use of Open3 for command execution
  • ⚠️ Consider caching webpack builds when possible to speed up repeated bin/dev prod calls

💡 Suggestions for Improvement

  1. Add specs for new functionality:

    describe "run_from_command_line" do
      it "parses route option correctly"
      it "handles rails-env override"
      it "maintains backward compatibility"
    end
  2. Consider extracting complex error handling:

    class AssetPrecompileErrorHandler
      def self.handle(stdout, stderr, command)
        # Centralized error analysis and guidance
      end
    end
  3. Add integration test for the full flow:

    • Test that bin/dev prod --route=dashboard actually works end-to-end
  4. Document the environment variable behavior more clearly in the README or main docs

Overall Assessment

This is a high-quality PR that significantly improves the developer experience. The code is well-structured, backward compatible, and adds valuable functionality. The main areas for improvement are around test coverage and method complexity reduction. Once those are addressed, this will be an excellent addition to the codebase.

Recommendation: Approve with minor suggestions for test coverage and refactoring opportunities.

Great work on this enhancement! 🎉

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review for PR #1790: Enhance bin/dev with configurable routes and improved production asset handling

🎯 Overall Assessment

This PR significantly improves the developer experience with the bin/dev script. The enhancements are well-structured and add valuable functionality. However, there are several areas that need attention before merging.

✅ Strengths

  1. Excellent abstraction: Moving command-line logic to ReactOnRails::Dev::ServerManager.run_from_command_line() improves testability and maintainability
  2. Better error handling: Comprehensive error output capture with contextual debugging guidance is very helpful
  3. Smart defaults: NODE_ENV=production + RAILS_ENV=development combination is pragmatic for testing production builds
  4. Good documentation: Clear help text and inline documentation explaining environment variables
  5. Backwards compatibility: All existing commands work without breaking changes

🔍 Code Quality Issues

1. Complexity in run_production_like method (lib/react_on_rails/dev/server_manager.rb:281-374)

  • Method has high complexity (disabled Rubocop metrics indicate this)
  • Consider extracting asset precompilation logic to a separate method
  • Error handling section could be its own method for better readability

2. Nil-safety inconsistency (lib/react_on_rails/configuration.rb:287-288, 336-337)

Using &. operator inconsistently - sometimes with packer_type&.upcase_first, sometimes without. Should be consistent throughout.

3. Magic numbers (lib/react_on_rails/dev/server_manager.rb)

Port numbers (3000, 3001) are hardcoded. Consider making these configurable or at least constants.

⚠️ Potential Bugs

1. Route parameter validation

No validation for the --route parameter. Malformed routes could cause issues.

2. Rails environment validation

The --rails-env parameter accepts any value without validation. Consider limiting to valid Rails environments.

🔒 Security Considerations

  1. ✅ Command injection: Good use of array form for system commands prevents injection
  2. ✅ Environment variable handling: Proper isolation of environment variables
  3. ⚠️ Output sanitization: Consider truncating extremely long outputs to prevent terminal flooding

🧪 Test Coverage Concerns

The PR description mentions tests were run, but I don't see new test files for:

  • ReactOnRails::Dev::ServerManager.run_from_command_line
  • Route parameter functionality
  • Rails environment override behavior

Recommendation: Add specs in spec/react_on_rails/dev/server_manager_spec.rb

📝 Specific Recommendations

  1. Extract error handling logic into smaller, focused methods
  2. Add input validation for route and rails_env parameters
  3. Create constants for magic values (ports, environment names)
  4. Add test coverage for new functionality
  5. Consider adding a --dry-run option to show what would be executed

🎬 Conclusion

This is a valuable enhancement that significantly improves the developer experience. With the suggested improvements to code organization, input validation, and test coverage, this will be a solid addition to the codebase.

Recommendation: Address the complexity issues and add test coverage before merging. The functionality is great, but needs refinement for long-term maintainability.

Great work on improving the developer workflow! 🚀

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review: bin/dev Enhancement PR #1790

I've reviewed this PR and found it to be a well-structured enhancement. The refactoring improves maintainability, adds useful features like configurable routes and improved error handling with Open3.capture3, and maintains backwards compatibility.

Strengths:

  • Clean architecture with run_from_command_line() method
  • Excellent error handling with contextual debugging hints
  • Thoughtful UX with --route and --rails-env parameters
  • Good documentation updates

Suggestions:

  • Add input validation for --rails-env parameter
  • Wrap Open3.capture3 in begin/rescue for robustness
  • Consider sanitizing the route parameter for security
  • Add tests for new command-line argument handling

Overall: High-quality PR that meaningfully improves developer experience. Approve with minor suggestions.

- Restore proper PackerUtils.using_packer? logic from master branch
- Fix precompile? method to handle missing shakapacker properly
- Update bin/dev tests to match new simplified template structure
- Update server_manager_spec to expect Open3.capture3 instead of system

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Sep 18, 2025

🔍 Code Review - PR #1790

Thank you for this comprehensive enhancement to the bin/dev script! I have reviewed the changes and have feedback on code quality, potential issues, performance, security, and test coverage.

Strengths

  1. Excellent abstraction - Moving command-line logic to ServerManager.run_from_command_line() improves maintainability
  2. Good error handling - The enhanced error messages with actionable guidance for bin/dev prod failures are very helpful
  3. Backwards compatibility - All existing commands continue to work as expected
  4. Code consolidation - Removing duplicate bin/dev files and using templates as single source of truth is a solid architectural improvement
  5. Safe nil handling - Adding nil-safe operators for PackerUtils.packer_type calls prevents potential crashes

🎯 Code Quality & Best Practices

1. Missing --rails-env Option Handling

The PR description mentions --rails-env=production option, but the implementation in run_from_command_line does not fully handle it in some of the commits. The latest commit appears to address this.

2. Hardcoded Shakapacker References

In lib/react_on_rails/configuration.rb:178, there is a hardcoded "shakapacker" string that should use the dynamic packer name for consistency.

🐛 Potential Bugs

1. Error Output Not Displayed

In run_production_like, using Open3.capture3 but not showing the stderr output to users when precompilation fails. This makes debugging harder. Consider displaying stderr when status.success? is false.

2. Missing Test Updates

Some tests were updated to use run_from_command_line but comprehensive tests for the new options are missing.

Performance Considerations

  1. Good use of Open3.capture3 - Better than system() for capturing output
  2. Consider parallel asset compilation - For production mode, might benefit from RAILS_GROUPS=assets to skip loading unnecessary groups

🔒 Security Concerns

No significant security issues found. The command construction is safe and does not use user input directly in shell commands.

🧪 Test Coverage

Missing test scenarios for:

  1. Command-line option parsing (--route and --rails-env options)
  2. Error message display verification
  3. Edge cases with invalid routes or rails_env values

📋 Documentation Notes

The markdown formatting fixes in the documentation are good improvements for readability.

🎬 Summary

This is a well-thought-out enhancement that significantly improves the developer experience. The main areas that could use attention are:

  1. Ensuring stderr output is shown when precompilation fails
  2. Adding comprehensive tests for the new command-line options
  3. Using dynamic packer names consistently throughout

The architectural improvements and enhanced error handling are particularly valuable contributions.

Great work on consolidating the bin/dev logic and making it more maintainable! 🚀

- Use instance_double instead of double for Process::Status
- Break long line for readability

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Sep 18, 2025

Code Review: Enhance bin/dev with configurable routes and improved production asset handling

Great work on this enhancement! The implementation provides valuable improvements to the development workflow. Here's my comprehensive review:

✅ Strengths

  1. Excellent Architecture Improvements

    • Smart consolidation of bin/dev scripts into templates reduces duplication
    • Clean abstraction with run_from_command_line() method
    • Well-structured option parsing using Ruby's OptionParser
  2. Developer Experience Enhancements

    • Configurable route display is a thoughtful addition for multi-route applications
    • Clear, informative help documentation with colored output
    • Helpful error messages with debugging guidance and specific fixes
  3. Production Testing Improvements

    • Smart defaults (NODE_ENV=production, RAILS_ENV=development) avoid credential complexity
    • Optional full production environment with --rails-env flag provides flexibility
    • Detailed environment explanations help developers understand the implications

🔍 Areas for Consideration

1. Potential Bug: Nil-safe Operator Usage

In lib/react_on_rails/configuration.rb:287 and similar locations:

packer_name = ReactOnRails::PackerUtils.packer_type&.upcase_first

The nil-safe operator is good, but if packer_type returns nil, the error messages will show "nil" instead of a meaningful packer name. Consider adding a fallback:

packer_name = ReactOnRails::PackerUtils.packer_type&.upcase_first || "Packer"

2. Error Handling Edge Case

In lib/react_on_rails/dev/server_manager.rb:295-296, the Open3.capture3 usage is good, but consider handling interrupt signals:

begin
  stdout, stderr, status = Open3.capture3(command)
rescue Interrupt
  puts "\n⚠️  Asset precompilation interrupted by user"
  exit 1
end

3. Performance Consideration

The error content analysis in lines 331-345 performs multiple string searches on potentially large output. Consider combining into a single pass or using a case statement with regex for better performance.

4. Documentation Formatting

While the markdown formatting improvements in the docs are good, some code blocks lost their language specifiers (e.g., bash or javascript), which could affect syntax highlighting.

🔒 Security Considerations

  • ✅ No credential exposure in logs or error messages
  • ✅ Proper use of HEREDOC for command execution prevents injection
  • ✅ Environment variable handling appears secure

🧪 Test Coverage

The test updates look appropriate, but consider adding specific tests for:

  • The new --route parameter functionality
  • The --rails-env override behavior
  • Error handling with malformed options

💡 Suggestions

  1. Add validation for route parameter: Ensure the route doesn't contain invalid characters or path traversal attempts
  2. Consider adding a --port option: For consistency with the route customization
  3. Add command aliases: Short forms like -r for --route would improve usability

🎯 Overall Assessment

This is a well-thought-out enhancement that significantly improves the development experience. The code quality is high, with good separation of concerns and helpful user feedback. The backwards compatibility is maintained perfectly.

Recommendation: Approve with minor suggestions

The PR is ready to merge after addressing the nil-safe operator fallback issue. The other suggestions are optional improvements that could be addressed in follow-up PRs.

Excellent work on making the development workflow more flexible and user-friendly! 🚀

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (5)
spec/react_on_rails/dev/server_manager_spec.rb (2)

57-59: Prefer Open3 with explicit env hash and argv array; assert RAILS_ENV default explicitly

Using a shell string is brittle (platform/env quoting) and doesn’t verify the intended default of RAILS_ENV=development. Recommend passing env/argv to Open3 and asserting the explicit RAILS_ENV to make the test resilient and aligned with the PR’s intent.

-      command = "NODE_ENV=production bundle exec rails assets:precompile"
-      status_double = instance_double(Process::Status, success?: true)
-      expect(Open3).to receive(:capture3).with(command).and_return(["output", "", status_double])
+      env = { "NODE_ENV" => "production", "RAILS_ENV" => "development" }
+      args = %w[bundle exec rails assets:precompile]
+      status_double = instance_double(Process::Status, success?: true)
+      expect(Open3).to receive(:capture3).with(env, *args).and_return(["output", "", status_double])

If the implementation intentionally omits RAILS_ENV, please confirm Rails’ default for assets:precompile across supported versions to avoid surprises.


9-19: Close the File::NULL IOs to avoid leaking FDs

You swap $stdout/$stderr to new IOs but never close them. Close the opened IOs in teardown to prevent descriptor leaks in long test runs.

   before(:all) do
-    @original_stderr = $stderr
-    @original_stdout = $stdout
-    $stderr = File.open(File::NULL, "w")
-    $stdout = File.open(File::NULL, "w")
+    @original_stderr = $stderr
+    @original_stdout = $stdout
+    @null_stderr = File.open(File::NULL, "w")
+    @null_stdout = File.open(File::NULL, "w")
+    $stderr = @null_stderr
+    $stdout = @null_stdout
   end

   after(:all) do
+    @null_stderr&.close
+    @null_stdout&.close
     $stderr = @original_stderr
     $stdout = @original_stdout
   end
spec/react_on_rails/binstubs/dev_spec.rb (3)

50-57: Add a case to verify ARGV is forwarded unchanged (with real args)

Current test forwards empty ARGV. Add a concrete-args example to prevent regressions when parsing flags like --route and --rails-env.

   it "with ReactOnRails::Dev loaded, delegates to ServerManager" do
     setup_script_execution_for_tool_tests
     allow(ReactOnRails::Dev::ServerManager).to receive(:run_from_command_line)

     # Mock the require to succeed
     allow_any_instance_of(Kernel).to receive(:require).with("bundler/setup").and_return(true)
     allow_any_instance_of(Kernel).to receive(:require).with("react_on_rails/dev").and_return(true)

     expect(ReactOnRails::Dev::ServerManager).to receive(:run_from_command_line).with(ARGV)

     load script_path
   end
+
+  it "forwards CLI args to ServerManager unchanged" do
+    setup_script_execution_for_tool_tests
+    args = %w[--route=/hello --rails-env=production]
+    stub_const("ARGV", args)
+    allow_any_instance_of(Kernel).to receive(:require).and_return(true)
+    expect(ReactOnRails::Dev::ServerManager).to receive(:run_from_command_line).with(args)
+    load script_path
+  end

21-26: Minor: avoid allow_any_instance_of(Kernel).

RuboCop RSpec discourages any_instance stubs. Prefer stubbing the specific calls invoked by the script or isolate via a wrapper.


9-19: Unify stdout/stderr suppression style across specs and close IOs

This file uses local vars vs. instance vars in server_manager_spec. Consider consistent pattern and close the opened IOs in teardown.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4141a39 and c4d2160.

📒 Files selected for processing (2)
  • spec/react_on_rails/binstubs/dev_spec.rb (2 hunks)
  • spec/react_on_rails/dev/server_manager_spec.rb (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.rb

📄 CodeRabbit inference engine (CLAUDE.md)

Use RuboCop for all Ruby code

Files:

  • spec/react_on_rails/dev/server_manager_spec.rb
  • spec/react_on_rails/binstubs/dev_spec.rb
🧠 Learnings (1)
📚 Learning: 2025-04-26T21:55:55.874Z
Learnt from: alexeyr-ci2
PR: shakacode/react_on_rails#1732
File: spec/dummy/client/app-react16/startup/ReduxSharedStoreApp.client.jsx:40-44
Timestamp: 2025-04-26T21:55:55.874Z
Learning: In the react_on_rails project, files under `app-react16` directories are copied/moved to corresponding `/app` directories during the conversion process (removing the `-react16` suffix), which affects their relative import paths at runtime.

Applied to files:

  • spec/react_on_rails/binstubs/dev_spec.rb
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (10)
  • GitHub Check: dummy-app-integration-tests (3.4, 22)
  • GitHub Check: dummy-app-integration-tests (3.2, 20)
  • GitHub Check: examples (3.2, minimum)
  • GitHub Check: rspec-package-tests (3.4, minimum)
  • GitHub Check: rspec-package-tests (3.2, latest)
  • GitHub Check: rspec-package-tests (3.4, latest)
  • GitHub Check: rspec-package-tests (3.2, minimum)
  • GitHub Check: build
  • GitHub Check: claude-review
  • GitHub Check: examples (3.4, latest)
🔇 Additional comments (2)
spec/react_on_rails/binstubs/dev_spec.rb (2)

6-6: Template path matches generator source; LGTM

Path aligns with install_generator’s template_bin_path. Nothing else to change here.


43-46: Good: assert delegation symbolically rather than mode branching

The content check for run_from_command_line keeps the bin script thin and future‑proof.

@justin808 justin808 requested a review from Copilot September 18, 2025 06:09
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

Copilot reviewed 11 out of 14 changed files in this pull request and generated 3 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment on lines +119 to +139
def run_from_command_line(args = ARGV)
require "optparse"

options = { route: nil, rails_env: nil }

OptionParser.new do |opts|
opts.banner = "Usage: dev [command] [options]"

opts.on("--route ROUTE", "Specify the route to display in URLs (default: root)") do |route|
options[:route] = route
end

opts.on("--rails-env ENV", "Override RAILS_ENV for assets:precompile step only (prod mode only)") do |env|
options[:rails_env] = env
end

opts.on("-h", "--help", "Prints this help") do
show_help
exit
end
end.parse!(args)
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The OptionParser instance is created but not assigned to a variable. While this works, storing it in a variable would make the code more readable and easier to test.

Copilot uses AI. Check for mistakes.
puts Rainbow("💡 Common fixes:").yellow.bold

# Provide specific guidance based on error content
error_content = "#{stderr} #{stdout}".downcase
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

String concatenation with interpolation creates unnecessary intermediate strings. Consider using [stderr, stdout].join(' ').downcase or check each stream separately to avoid creating the combined string.

Suggested change
error_content = "#{stderr} #{stdout}".downcase
error_content = [stderr, stdout].map(&:to_s).join(' ').downcase

Copilot uses AI. Check for mistakes.
Comment on lines +340 to +341
if error_content.include?("database") || error_content.include?("relation") ||
error_content.include?("table")
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] Multiple string checks could be simplified using a single regular expression: error_content.match?(/database|relation|table/) which would be more efficient and maintainable.

Suggested change
if error_content.include?("database") || error_content.include?("relation") ||
error_content.include?("table")
if error_content.match?(/database|relation|table/)

Copilot uses AI. Check for mistakes.
justin808 and others added 2 commits September 17, 2025 20:12
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Security improvements:
- Replace string interpolation with env hash and argv array for Open3.capture3
- Add rails_env validation with allowlist pattern (/^[a-z0-9_]+$/i)
- Update error handling to use safe command display
- Add tests for rails_env validation and custom environment usage
- Prevent arbitrary shell command execution via --rails-env parameter

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@claude
Copy link

claude bot commented Sep 18, 2025

🔍 Code Review for PR #1790: Enhanced bin/dev with Configurable Routes and Production Asset Handling

Overall Assessment

This PR represents a significant improvement to the development workflow with thoughtful architecture changes. The enhancements are well-designed, backwards compatible, and provide valuable developer experience improvements.

🌟 Key Strengths

  1. Excellent Architecture Refactoring

    • Clean separation of concerns by moving CLI logic to ServerManager.run_from_command_line()
    • Removal of duplicate lib/generators/react_on_rails/bin/dev consolidates to single source of truth
    • Proper use of Open3 for safe command execution with full output capture
  2. Developer Experience Improvements

    • Comprehensive error handling with contextual debugging guidance
    • Clear environment explanations (NODE_ENV vs RAILS_ENV) in production mode
    • Beautiful formatted output with Rainbow gem for better readability
    • Helpful error-specific recovery suggestions (database, webpack, credentials)
  3. Flexible Production Testing

    • Smart default of NODE_ENV=production with RAILS_ENV=development avoids credential complexity
    • Optional --rails-env=production for full production testing when needed
    • Clear separation of precompile environment from server process environment
  4. Strong Backwards Compatibility

    • All existing commands work unchanged
    • New options are additive and optional
    • Route parameter smartly defaults to root when not specified

🎯 Code Quality Highlights

  • Secure Command Execution: Good sanitization of rails_env parameter with regex validation
  • Proper Error Handling: Full stdout/stderr capture with detailed debugging instructions
  • Clean Code Organization: Well-structured help system with separate methods for each section
  • Good Test Coverage: Tests updated to verify new run_from_command_line interface

⚠️ Minor Suggestions for Improvement

  1. Shell Command Construction (lib/react_on_rails/dev/server_manager.rb:273-296)

    • The command string construction at line 273 is actually just for display purposes
    • The actual execution at line 296 correctly uses Open3.capture3 with the command string
    • Consider using env hash directly in Open3.capture3 for cleaner separation
  2. Test Coverage Enhancement

    • Consider adding tests for the new --route and --rails-env options in ServerManager spec
    • Test the regex validation for rails_env parameter to ensure security
  3. Configuration Validation (lib/react_on_rails/configuration.rb)

    • Good use of safe navigation operator (&.) for PackerUtils.packer_type calls
    • Prevents potential nil errors when packer is not configured

📊 Security & Performance

Security: Proper input validation for rails_env parameter prevents shell injection
Performance: No performance concerns - changes are primarily workflow improvements
Error Handling: Robust error recovery with clear user guidance

🚀 Impact Assessment

This PR successfully achieves its goals:

  • ✅ Production-quality webpack bundles without Rails production complexity by default
  • ✅ Flexible environment control for different testing scenarios
  • ✅ Better debugging with full error output and contextual guidance
  • ✅ Cleaner codebase with reduced duplication
  • ✅ Enhanced developer workflow with configurable URLs

💬 Summary

Excellent work! This PR demonstrates thoughtful design with strong attention to developer experience. The backwards compatibility, comprehensive error handling, and clear documentation make this a high-quality contribution. The flexible approach to production asset testing (NODE_ENV=production with RAILS_ENV=development by default) is particularly clever.

The code is clean, well-organized, and properly tested. Minor suggestions above are optional enhancements rather than required changes.

Recommendation: ✅ Approve and merge

cc @justin808 - This is a great enhancement to the development workflow! 🎉

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review for PR 1790: See detailed feedback below

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review - Part 1: Strengths

  1. Architecture Refactoring: Moving CLI logic to run_from_command_line() method improves maintainability and testability.

  2. Error Handling: Enhanced error output with contextual debugging in run_production_like() is helpful. Good capture of stdout/stderr.

  3. Security: Input validation for rails_env parameter with regex checking prevents shell injection.

  4. Developer Experience: The --route parameter and improved help documentation enhance usability.

  5. Backwards Compatibility: All existing commands work as expected while adding new optional features.

@claude
Copy link

claude bot commented Sep 18, 2025

Code Review - Part 2: Issues and Suggestions

Issues Found:

  1. Missing Test Coverage: New --route and --rails-env parameters lack comprehensive test coverage.

  2. Truncated Error Message: Line 366 in server_manager.rb has incomplete error message ending with 'Run #{Rai'.

  3. Nil Safety: Some ReactOnRails::PackerUtils.packer_type calls missing nil-safe operators (configuration.rb lines 287, 336).

Suggestions:

  1. Add validation to prevent incompatible option combinations
  2. Add timeout to Open3.capture3 calls
  3. Maintain consistent markdown code block formatting
  4. Add YARD documentation for new parameters

Testing Commands:

  • bin/dev prod --route=dashboard
  • bin/dev prod --rails-env=production
  • bin/dev static --route=admin

Overall: Well-designed enhancement. Fix the truncated error message and add test coverage before merging.

@justin808 justin808 requested a review from Copilot September 18, 2025 06:20
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

Copilot reviewed 11 out of 14 changed files in this pull request and generated 2 comments.


Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

# Validate and sanitize rails_env to prevent shell injection
if rails_env
unless rails_env.match?(/\A[a-z0-9_]+\z/i)
puts "❌ Invalid rails_env: '#{rails_env}'. Must contain only letters, numbers, and underscores."
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The regex validation for rails_env is case-insensitive but the error message only mentions lowercase letters. Either make the regex case-sensitive (/\A[a-z0-9_]+\z/) or update the error message to mention 'letters (case-insensitive)'.

Suggested change
puts "❌ Invalid rails_env: '#{rails_env}'. Must contain only letters, numbers, and underscores."
puts "❌ Invalid rails_env: '#{rails_env}'. Must contain only letters (case-insensitive), numbers, and underscores."

Copilot uses AI. Check for mistakes.
puts Rainbow("💡 Common fixes:").yellow.bold

# Provide specific guidance based on error content
error_content = "#{stderr} #{stdout}".downcase
Copy link

Copilot AI Sep 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider using string interpolation more efficiently here: error_content = [stderr, stdout].join(' ').downcase to avoid potential issues if either stderr or stdout is nil.

Suggested change
error_content = "#{stderr} #{stdout}".downcase
error_content = [stderr, stdout].compact.join(' ').downcase

Copilot uses AI. Check for mistakes.
@justin808 justin808 merged commit ce30d89 into master Sep 18, 2025
14 checks passed
@justin808 justin808 deleted the feature/bin-dev-extraction branch September 18, 2025 06:22
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.

2 participants