Class: ReactOnRails::SystemChecker

Inherits:
Object
  • Object
show all
Defined in:
lib/react_on_rails/system_checker.rb

Overview

SystemChecker provides validation methods for React on Rails setup Used by install generator and doctor rake task rubocop:disable Metrics/ClassLength

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSystemChecker

Returns a new instance of SystemChecker.



12
13
14
# File 'lib/react_on_rails/system_checker.rb', line 12

def initialize
  @messages = []
end

Instance Attribute Details

#messagesObject (readonly)

Returns the value of attribute messages.



10
11
12
# File 'lib/react_on_rails/system_checker.rb', line 10

def messages
  @messages
end

Instance Method Details

#add_error(message) ⇒ Object



16
17
18
# File 'lib/react_on_rails/system_checker.rb', line 16

def add_error(message)
  @messages << { type: :error, content: message }
end

#add_info(message) ⇒ Object



28
29
30
# File 'lib/react_on_rails/system_checker.rb', line 28

def add_info(message)
  @messages << { type: :info, content: message }
end

#add_success(message) ⇒ Object



24
25
26
# File 'lib/react_on_rails/system_checker.rb', line 24

def add_success(message)
  @messages << { type: :success, content: message }
end

#add_warning(message) ⇒ Object



20
21
22
# File 'lib/react_on_rails/system_checker.rb', line 20

def add_warning(message)
  @messages << { type: :warning, content: message }
end

#bundle_analyzer_available?Boolean

Returns:

  • (Boolean)


336
337
338
339
340
341
342
343
344
345
346
# File 'lib/react_on_rails/system_checker.rb', line 336

def bundle_analyzer_available?
  return false unless File.exist?("package.json")

  begin
    package_json = JSON.parse(File.read("package.json"))
    all_deps = package_json["dependencies"]&.merge(package_json["devDependencies"] || {}) || {}
    all_deps["webpack-bundle-analyzer"]
  rescue StandardError
    false
  end
end

#check_node_installationObject

Node.js validation



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/react_on_rails/system_checker.rb', line 41

def check_node_installation
  if node_missing?
    add_error(<<~MSG.strip)
      🚫 Node.js is required but not found on your system.

      Please install Node.js before continuing:
      • Download from: https://nodejs.org/en/
      • Recommended: Use a version manager like nvm, fnm, or volta
      • Minimum required version: Node.js 18+

      After installation, restart your terminal and try again.
    MSG
    return false
  end

  check_node_version
  true
end

#check_node_versionObject



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/react_on_rails/system_checker.rb', line 60

def check_node_version
  stdout, stderr, status = Open3.capture3("node", "--version")

  # Use stdout if available, fallback to stderr if stdout is empty
  node_version = stdout.strip
  node_version = stderr.strip if node_version.empty?

  # Return early if node is not found (non-zero status) or no output
  return if !status.success? || node_version.empty?

  # Extract major version number (e.g., "v18.17.0" -> 18)
  major_version = node_version[/v(\d+)/, 1]&.to_i
  return unless major_version

  if major_version < 18
    add_warning(<<~MSG.strip)
      ⚠️  Node.js version #{node_version} detected.

      React on Rails recommends Node.js 18+ for best compatibility.
      You may experience issues with older versions.

      Consider upgrading: https://nodejs.org/en/
    MSG
  else
    add_success("✅ Node.js #{node_version} is installed and compatible")
  end
end

#check_package_managerObject

Package manager validation



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/react_on_rails/system_checker.rb', line 89

def check_package_manager
  package_managers = %w[npm pnpm yarn bun]
  available_managers = package_managers.select { |pm| cli_exists?(pm) }

  if available_managers.empty?
    add_error(<<~MSG.strip)
      🚫 No JavaScript package manager found on your system.

      React on Rails requires a JavaScript package manager to install dependencies.
      Please install one of the following:

      • npm: Usually comes with Node.js (https://nodejs.org/en/)
      • yarn: npm install -g yarn (https://yarnpkg.com/)
      • pnpm: npm install -g pnpm (https://pnpm.io/)
      • bun: Install from https://bun.sh/

      After installation, restart your terminal and try again.
    MSG
    return false
  end

  # Detect which package manager is actually being used
  used_manager = detect_used_package_manager
  if used_manager
    version_info = get_package_manager_version(used_manager)
    deprecation_note = get_deprecation_note(used_manager, version_info)
    message = "✅ Package manager in use: #{used_manager} #{version_info}"
    message += deprecation_note if deprecation_note
    add_success(message)
  else
    add_success("✅ Package managers available: #{available_managers.join(', ')}")
    add_info("ℹ️  No lock file detected - run npm/yarn/pnpm install to establish which manager is used")
  end
  true
end

#check_package_version_syncObject

rubocop:disable Metrics/CyclomaticComplexity



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/react_on_rails/system_checker.rb', line 206

def check_package_version_sync # rubocop:disable Metrics/CyclomaticComplexity
  return unless File.exist?("package.json")

  begin
    package_json = JSON.parse(File.read("package.json"))
    npm_version = package_json.dig("dependencies", "react-on-rails") ||
                  package_json.dig("devDependencies", "react-on-rails")

    return unless npm_version && defined?(ReactOnRails::VERSION)

    # Clean version strings for comparison (remove ^, ~, =, etc.)
    clean_npm_version = npm_version.gsub(/[^0-9.]/, "")
    gem_version = ReactOnRails::VERSION

    if clean_npm_version == gem_version
      add_success("✅ React on Rails gem and NPM package versions match (#{gem_version})")
      check_version_patterns(npm_version, gem_version)
    else
      # Check for major version differences
      gem_major = gem_version.split(".")[0].to_i
      npm_major = clean_npm_version.split(".")[0].to_i

      if gem_major != npm_major # rubocop:disable Style/NegatedIfElseCondition
        add_error(<<~MSG.strip)
          🚫 Major version mismatch detected:
          • Gem version: #{gem_version} (major: #{gem_major})
          • NPM version: #{npm_version} (major: #{npm_major})

          Major version differences can cause serious compatibility issues.
          Update both packages to use the same major version immediately.
        MSG
      else
        add_warning(<<~MSG.strip)
          ⚠️  Version mismatch detected:
          • Gem version: #{gem_version}
          • NPM version: #{npm_version}

          Consider updating to exact, fixed matching versions of gem and npm package for best compatibility.
        MSG
      end
    end
  rescue JSON::ParserError
    # Ignore parsing errors, already handled elsewhere
  rescue StandardError
    # Handle other errors gracefully
  end
end

#check_react_dependenciesObject

React dependencies validation



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/react_on_rails/system_checker.rb', line 255

def check_react_dependencies
  return unless File.exist?("package.json")

  package_json = parse_package_json
  return unless package_json

  # Check core React dependencies
  required_deps = required_react_dependencies
  missing_deps = find_missing_dependencies(package_json, required_deps)
  report_dependency_status(required_deps, missing_deps, package_json)

  # Check additional build dependencies (informational)
  check_build_dependencies(package_json)

  # Report versions
  report_dependency_versions(package_json)
end

#check_react_on_rails_gemObject



170
171
172
173
174
175
176
177
178
179
180
181
182
# File 'lib/react_on_rails/system_checker.rb', line 170

def check_react_on_rails_gem
  require "react_on_rails"
  add_success("✅ React on Rails gem #{ReactOnRails::VERSION} is loaded")
rescue LoadError
  add_error(<<~MSG.strip)
    🚫 React on Rails gem is not available.

    Add to your Gemfile:
    gem 'react_on_rails'

    Then run: bundle install
  MSG
end

#check_react_on_rails_initializerObject

Rails integration validation



275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/react_on_rails/system_checker.rb', line 275

def check_react_on_rails_initializer
  initializer_path = "config/initializers/react_on_rails.rb"
  if File.exist?(initializer_path)
    add_success("✅ React on Rails initializer exists")
  else
    add_warning(<<~MSG.strip)
      ⚠️  React on Rails initializer not found.

      Create: config/initializers/react_on_rails.rb
      Or run: rails generate react_on_rails:install
    MSG
  end
end

#check_react_on_rails_npm_packageObject



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/react_on_rails/system_checker.rb', line 184

def check_react_on_rails_npm_package
  package_json_path = "package.json"
  return unless File.exist?(package_json_path)

  package_json = JSON.parse(File.read(package_json_path))
  npm_version = package_json.dig("dependencies", "react-on-rails") ||
                package_json.dig("devDependencies", "react-on-rails")

  if npm_version
    add_success("✅ react-on-rails NPM package #{npm_version} is declared")
  else
    add_warning(<<~MSG.strip)
      ⚠️  react-on-rails NPM package not found in package.json.

      Install it with:
      npm install react-on-rails
    MSG
  end
rescue JSON::ParserError
  add_warning("⚠️  Could not parse package.json")
end

#check_react_on_rails_packagesObject

React on Rails package validation



163
164
165
166
167
168
# File 'lib/react_on_rails/system_checker.rb', line 163

def check_react_on_rails_packages
  check_react_on_rails_gem
  check_react_on_rails_npm_package
  check_package_version_sync
  check_gemfile_version_patterns
end

#check_shakapacker_configurationObject

Shakapacker validation



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/react_on_rails/system_checker.rb', line 126

def check_shakapacker_configuration
  unless shakapacker_configured?
    add_error(<<~MSG.strip)
      🚫 Shakapacker is not properly configured.

      Missing one or more required files:
      • bin/shakapacker
      • bin/shakapacker-dev-server
      • config/shakapacker.yml
      • config/webpack/webpack.config.js

      Run: bundle exec rails shakapacker:install
    MSG
    return false
  end

  report_shakapacker_version_with_threshold
  check_shakapacker_in_gemfile
  true
end

#check_shakapacker_in_gemfileObject



147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/react_on_rails/system_checker.rb', line 147

def check_shakapacker_in_gemfile
  if shakapacker_in_gemfile?
    add_success("✅ Shakapacker is declared in Gemfile")
  else
    add_warning(<<~MSG.strip)
      ⚠️  Shakapacker not found in Gemfile.

      While Shakapacker might be available as a dependency,
      it's recommended to add it explicitly to your Gemfile:

      bundle add shakapacker --strict
    MSG
  end
end

#check_webpack_config_contentObject



348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/react_on_rails/system_checker.rb', line 348

def check_webpack_config_content
  webpack_config_path = "config/webpack/webpack.config.js"
  content = File.read(webpack_config_path)

  if react_on_rails_config?(content)
    add_success("✅ Webpack config includes React on Rails environment configuration")
    add_info("    ℹ️  Environment-specific configs detected for optimal React on Rails integration")
  elsif standard_shakapacker_config?(content)
    add_warning(<<~MSG.strip)
      ⚠️  Standard Shakapacker webpack config detected.

      React on Rails works better with environment-specific configuration.
      Consider running: rails generate react_on_rails:install --force
      This adds client and server environment configs for better performance.
    MSG
  else
    add_info("ℹ️  Custom webpack config detected")
    add_info("    💡 Ensure config supports both client and server rendering")
    add_info("    💡 Verify React JSX transformation is configured")
    add_info("    💡 Check that asset output paths match Rails expectations")
  end
end

#check_webpack_configurationObject

Webpack configuration validation



290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# File 'lib/react_on_rails/system_checker.rb', line 290

def check_webpack_configuration
  webpack_config_path = "config/webpack/webpack.config.js"
  if File.exist?(webpack_config_path)
    add_success("✅ Webpack configuration exists")
    check_webpack_config_content
    suggest_webpack_inspection
  else
    add_error(<<~MSG.strip)
      🚫 Webpack configuration not found.

      Expected: config/webpack/webpack.config.js
      Run: rails generate react_on_rails:install
    MSG
  end
end

#errors?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/react_on_rails/system_checker.rb', line 32

def errors?
  @messages.any? { |msg| msg[:type] == :error }
end

#suggest_webpack_inspectionObject



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# File 'lib/react_on_rails/system_checker.rb', line 306

def suggest_webpack_inspection
  add_info("💡 To debug webpack builds:")
  add_info("    bin/shakapacker --mode=development --progress")
  add_info("    bin/shakapacker --mode=production --progress")
  add_info("    bin/shakapacker --debug-shakapacker  # Debug Shakapacker configuration")

  add_info("💡 Advanced webpack debugging:")
  add_info("    1. Add 'debugger;' before 'module.exports' in config/webpack/webpack.config.js")
  add_info("    2. Run: ./bin/shakapacker --debug-shakapacker")
  add_info("    3. Open Chrome DevTools to inspect config object")
  add_info("    📖 See: https://github.com/shakacode/shakapacker/blob/main/docs/troubleshooting.md#debugging-your-webpack-config")

  add_info("💡 To analyze bundle size:")
  if bundle_analyzer_available?
    add_info("    ANALYZE=true bin/shakapacker")
    add_info("    This opens webpack-bundle-analyzer in your browser")
  else
    add_info("    1. yarn add --dev webpack-bundle-analyzer")
    add_info("    2. Add to config/webpack/webpack.config.js:")
    add_info("       const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');")
    add_info("       // Add to plugins array when process.env.ANALYZE")
    add_info("    3. ANALYZE=true bin/shakapacker")
    add_info("    Or use Shakapacker's built-in support if available")
  end

  add_info("💡 Generate webpack stats for analysis:")
  add_info("    bin/shakapacker --json > webpack-stats.json")
  add_info("    Upload to webpack.github.io/analyse or webpack-bundle-analyzer.com")
end

#warnings?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'lib/react_on_rails/system_checker.rb', line 36

def warnings?
  @messages.any? { |msg| msg[:type] == :warning }
end