-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.rb
More file actions
2555 lines (2090 loc) · 80 KB
/
template.rb
File metadata and controls
2555 lines (2090 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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
87
88
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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Unified Rails Application Template
# Usage:
# rails new APP_NAME \
# --database=postgresql \
# --javascript=esbuild \
# --css=bootstrap (or --css=tailwind) \
# --skip-test \
# --skip-kamal \
# --skip-rubocop \
# -m /path/to/this/template.rb
base_url = "https://raw.githubusercontent.com/firstdraft/rails_application_template/main"
# === CONFIGURATION OPTIONS ===
say "\n=== Rails Application Template ===", :yellow
say "\nThis template will configure your Rails app with modern best practices.", :cyan
say "\nDefault configuration includes:", :yellow
say "\nEssential Tools (always included):", :green
say " • RSpec & FactoryBot - Testing framework"
say " • StandardRB - Ruby code formatting"
say " • Herb - HTML+ERB linting and analysis"
say " • Bullet - N+1 query detection"
say " • AnnotateRb - Auto-annotate models"
say " • Pry, Better Errors, Amazing Print - Debugging"
say " • Dotenv - Environment management"
say "\nDefault Optional Tools:", :green
say " ✅ SimpleCov - Code coverage"
say " ✅ Shoulda Matchers - One-liner tests"
say " ✅ Faker - Test data generation"
say " ❌ WebMock - HTTP stubbing (often not needed)"
say " ✅ Goldiloader - Auto N+1 prevention"
say " ✅ rack-mini-profiler - Development performance bar"
say " ✅ Skylight - Production performance monitoring"
say " ✅ Ahoy + Blazer - Analytics tracking and dashboard"
say " ✅ Rails ERD - Entity diagrams"
say " ❌ rails_db - Database web UI (security concern)"
say " ✅ Rollbar - Error tracking (default choice)"
say " ✅ Bootstrap overrides - Custom Sass variables file"
say " ❌ Full JS/CSS linting - Prettier, ESLint, Stylelint (not needed for all apps)"
say " ❌ UUID primary keys - Use UUIDs instead of integers (UUIDv7 default when enabled)"
say " ❌ Multi-database setup - Rails 8 separate databases (single DB is simpler for deployment)"
say " ❌ Render.com deployment - Build script and render.yaml blueprint"
say "\n"
customize = yes?("Would you like to customize these options? (y/n)")
# Set up configuration based on user choice
if customize
say "\n=== Customize Your Configuration ===", :yellow
say "Let's go through each optional tool:\n", :cyan
# Testing preferences
testing_options = {}
say "\nTesting Tools:", :yellow
testing_options[:simplecov] = yes?(" Include SimpleCov for code coverage? (y/n)")
testing_options[:shoulda] = yes?(" Include Shoulda Matchers for one-liner tests? (y/n)")
testing_options[:faker] = yes?(" Include Faker for test data generation? (y/n)")
testing_options[:webmock] = yes?(" Include WebMock for HTTP request stubbing? (y/n)")
# Performance monitoring
performance_options = {}
say "\nPerformance Tools:", :yellow
performance_options[:goldiloader] = yes?(" Include Goldiloader for automatic N+1 prevention? (y/n)")
performance_options[:rack_profiler] = yes?(" Include rack-mini-profiler for development performance bar? (y/n)")
performance_options[:skylight] = yes?(" Include Skylight for production performance monitoring? (y/n)")
# Analytics
analytics_options = {}
say "\nAnalytics:", :yellow
analytics_options[:ahoy_blazer] = yes?(" Include Ahoy + Blazer for analytics tracking and dashboard? (y/n)")
# Documentation tools
doc_options = {}
say "\nDocumentation Tools:", :yellow
doc_options[:rails_erd] = yes?(" Include Rails ERD for entity relationship diagrams? (y/n)")
doc_options[:rails_db] = yes?(" Include rails_db for web-based database UI? (y/n)")
# Error monitoring
monitoring_options = {}
say "\nError Monitoring:", :yellow
say " Choose error monitoring service:"
say " 1. Rollbar (default)"
say " 2. Honeybadger"
say " 3. None"
monitoring_choice = ask(" Enter choice (1-3):", :limited_to => %w[1 2 3], :default => "1")
monitoring_options[:error_service] = case monitoring_choice
when "1"
"rollbar"
when "2"
"honeybadger"
when "3"
"none"
end
# Frontend tools
frontend_options = {}
say "\nFrontend Tools:", :yellow
frontend_options[:bootstrap_overrides] = yes?(" Include Bootstrap overrides file for easy customization? (y/n)")
frontend_options[:full_linting] = yes?(" Include full JS/CSS linting stack (Prettier, ESLint, Stylelint)? (y/n)")
# Database configuration
db_options = {}
say "\nDatabase Configuration:", :yellow
db_options[:use_uuid] = yes?(" Use UUIDs for primary keys instead of integers? (y/n)")
if db_options[:use_uuid]
say " UUID version:", :cyan
say " 1. UUID v7 (default, time-ordered)"
say " 2. UUID v4 (random)"
uuid_choice = ask(" Enter choice (1-2):", limited_to: %w[1 2], default: "1")
db_options[:uuid_version] = (uuid_choice == "1") ? :v7 : :v4
else
# Irrelevant unless UUIDs are enabled, but keeping a stable default simplifies downstream conditionals.
db_options[:uuid_version] = :v7
end
db_options[:multi_database] = yes?(" Use Rails 8 multi-database setup (separate DBs for cache/queue/cable)? (y/n)")
# Deployment configuration
render_options = {}
say "\nDeployment:", :yellow
render_options[:enabled] = yes?(" Configure for Render.com deployment (build script + render.yaml)? (y/n)")
if render_options[:enabled]
say "\n Render.com Plan:", :cyan
say " 1. Free tier (512MB RAM - good for demos, small apps)"
say " 2. Starter/Paid tier (more resources, better performance)"
tier_choice = ask(" Select tier (1-2):", limited_to: %w[1 2], default: "1")
render_options[:free_tier] = (tier_choice == "1")
say "\n Database Provider:", :cyan
if render_options[:free_tier]
say " → Using Supabase (recommended for free tier - no 90-day expiration)", :green
render_options[:database_provider] = "supabase"
else
say " 1. Render Postgres (integrated, simpler setup)"
say " 2. Supabase (more features: real-time, auth, storage, generous free tier)"
db_choice = ask(" Select option (1-2):", limited_to: %w[1 2], default: "1")
render_options[:database_provider] = (db_choice == "1") ? "render" : "supabase"
end
say "\n Background Jobs:", :cyan
say " 1. Run in web process (simpler, shares memory - recommended for free tier)"
say " 2. Separate worker service (isolated resources, costs more on paid tier)"
job_choice = ask(" Select option (1-2):", limited_to: %w[1 2], default: "1")
render_options[:separate_worker] = (job_choice == "2")
say "\n Custom Domain:", :cyan
if yes?(" Do you know your production domain? (y/n)")
render_options[:domain] = ask(" Enter domain (e.g., myapp.com):")
render_options[:include_www] = yes?(" Also configure www.#{render_options[:domain]}? (y/n)")
else
render_options[:domain] = nil
render_options[:include_www] = false
end
else
render_options[:separate_worker] = false
render_options[:free_tier] = true
render_options[:database_provider] = "supabase"
render_options[:domain] = nil
render_options[:include_www] = false
end
# CI/CD configuration
ci_options = {}
say "\nCI/CD:", :yellow
ci_options[:github_actions] = yes?(" Include GitHub Actions CI workflow? (y/n)")
else
# Use default configuration
testing_options = {
simplecov: true,
shoulda: true,
faker: true,
webmock: false
}
performance_options = {
goldiloader: true,
rack_profiler: true,
skylight: true
}
analytics_options = {
ahoy_blazer: true
}
doc_options = {
rails_erd: true,
rails_db: false
}
monitoring_options = {
error_service: "rollbar"
}
frontend_options = {
bootstrap_overrides: true,
full_linting: false
}
db_options = {
use_uuid: false,
uuid_version: :v7,
multi_database: false
}
render_options = {
enabled: false,
separate_worker: false,
free_tier: true,
database_provider: "supabase",
domain: nil,
include_www: false
}
ci_options = {
github_actions: true
}
say "\n✅ Using default configuration!", :green
end
# === GEMS CONFIGURATION ===
# Automatic N+1 prevention (all environments)
if performance_options[:goldiloader]
gem "goldiloader"
end
gem_group :development, :test do
# Essential Debugging (always included)
# Rails uses IRB by default; `debug` is the modern Ruby debugger. `pry` is an optional enhanced REPL.
unless File.read("Gemfile").match?(/^\s*gem\s+["']debug["']/)
gem "debug", platforms: %i[mri mingw x64_mingw]
end
unless File.read("Gemfile").match?(/^\s*gem\s+["']pry["']/)
gem "pry"
end
# Temporarily disabled: not Ruby 4-ready (re-enable when compatible)
# gem "better_errors"
# gem "binding_of_caller"
gem "amazing_print"
# Environment (always included)
gem "dotenv"
# Testing Framework (always included)
gem "rspec-rails", "~> 7.1"
gem "factory_bot_rails"
# Optional Testing Tools
gem "shoulda-matchers", "~> 6.0" if testing_options[:shoulda]
gem "faker" if testing_options[:faker]
# Code Quality (always included)
gem "standard", require: false
gem "standard-rails", require: false
gem "herb", require: false
# Security scanning (used in README + CI)
unless File.read("Gemfile").match?(/^\s*gem\s+["']bundler-audit["']/)
gem "bundler-audit", require: false
end
# N+1 Query Detection (always included in dev/test)
gem "bullet"
# ERB Linting (only with full linting)
if frontend_options[:full_linting]
gem "better_html", require: false
gem "erb_lint", require: false
gem "erblint-github", require: false
end
end
gem_group :development do
# Optional Performance Tools
gem "rack-mini-profiler" if performance_options[:rack_profiler]
# Documentation (annotaterb always included)
gem "annotaterb"
gem "rails-erd" if doc_options[:rails_erd]
gem "rails_db", ">= 2.3.1" if doc_options[:rails_db]
end
# Production performance monitoring
if performance_options[:skylight]
gem "skylight"
end
# Analytics
if analytics_options[:ahoy_blazer]
gem "ahoy_matey"
gem "blazer"
gem "chartkick" # For charts in Blazer
gem "groupdate" # For time-based grouping in Blazer
end
# Error Monitoring (outside of any group)
case monitoring_options[:error_service]
when "rollbar"
gem "rollbar"
when "honeybadger"
gem "honeybadger"
end
gem_group :test do
# System Testing (always included)
gem "capybara"
gem "selenium-webdriver"
# Optional Testing Tools
gem "webmock" if testing_options[:webmock]
gem "simplecov", require: false if testing_options[:simplecov]
end
# Keep the generated Gemfile clean and under our control.
# The default Rails Gemfile (and some generators) include lots of commentary; strip it out.
def strip_comments_from_gemfile!(path = "Gemfile")
lines = File.read(path).each_line.map do |line|
out = +""
in_single = false
in_double = false
escaped = false
line.each_char do |ch|
if escaped
out << ch
escaped = false
next
end
if (in_single || in_double) && ch == "\\"
out << ch
escaped = true
next
end
if !in_double && ch == "'"
in_single = !in_single
out << ch
next
end
if !in_single && ch == "\""
in_double = !in_double
out << ch
next
end
break if ch == "#" && !in_single && !in_double
out << ch
end
out = out.rstrip
out.strip.empty? ? "" : out
end
# Trim leading/trailing blank lines and collapse consecutive blanks.
lines.shift while lines.first == ""
lines.pop while lines.last == ""
collapsed = []
lines.each do |line|
next if line == "" && collapsed.last == ""
collapsed << line
end
File.write(path, collapsed.join("\n") + "\n")
end
strip_comments_from_gemfile!
# === AFTER BUNDLE ACTIONS ===
after_bundle do
# Initial database setup
rails_command("db:create")
git add: "-A"
git commit: "-m 'Initial Rails app with custom template'"
# === DATABASE CONFIGURATION ===
unless db_options[:multi_database]
say "Configuring single database for all environments (cache/queue/cable share primary DB)...", :cyan
# Use traditional single-database format for database.yml
remove_file "config/database.yml"
create_file "config/database.yml", <<~YAML
# PostgreSQL 18+ is required (this template assumes Postgres 18 features when UUIDs are enabled).
#
# Install the pg driver:
# gem install pg
# On macOS with Homebrew:
# gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On Windows:
# gem install pg
# Choose the win32 build.
# Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem "pg"
#
default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: #{app_name}_development
# The specified database role being used to connect to PostgreSQL.
# To create additional roles in PostgreSQL see `$ createuser --help`.
# When left blank, PostgreSQL will use the default role. This is
# the same name as the operating system user running Rails.
#username: #{app_name}
# The password associated with the PostgreSQL role (username).
#password:
# Connect on a TCP socket. Omitted by default since the client uses a
# domain socket that doesn't need configuration. Windows does not have
# domain sockets, so uncomment these lines.
#host: localhost
# The TCP port the server listens on. Defaults to 5432.
# If your server runs on a different port number, change accordingly.
#port: 5432
# Schema search path. The server defaults to $user,public
#schema_search_path: myapp,sharedapp,public
# Minimum log levels, in increasing order:
# debug5, debug4, debug3, debug2, debug1,
# log, notice, warning, error, fatal, and panic
# Defaults to warning.
#min_messages: notice
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: #{app_name}_test
# As with config/credentials.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password or a full connection URL as an environment
# variable when you boot the app. For example:
#
# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
#
# If the connection URL is provided in the special DATABASE_URL environment
# variable, Rails will automatically merge its configuration values on top of
# the values provided in this file. Alternatively, you can specify a connection
# URL environment variable explicitly:
#
# production:
# url: <%= ENV["MY_APP_DATABASE_URL"] %>
#
# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full overview on how database connection configuration can be specified.
#
production:
<<: *default
url: <%= ENV["DATABASE_URL"] %>
YAML
# Remove multi-database references from Solid Cache config
if File.exist?("config/cache.yml")
gsub_file "config/cache.yml",
/^\s*database: cache\n/,
""
end
# Remove multi-database references from Solid Cable config
if File.exist?("config/cable.yml")
gsub_file "config/cable.yml",
/\s*connects_to:\n\s*database:\n\s*writing: cable\n/,
"\n"
end
# Remove multi-database references from production environment
gsub_file "config/environments/production.rb",
/\s*config\.solid_queue\.connects_to = \{ database: \{ writing: :queue \} \}\n/,
"\n"
# Convert Solid schema files into regular migrations
# This ensures all tables are created in the primary database
timestamp = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
# Create migrations for cache, queue, and cable tables
if File.exist?("db/cache_schema.rb")
cache_schema = File.read("db/cache_schema.rb")
# Extract the content inside the schema definition
if cache_schema.match(/ActiveRecord::Schema.*?\.define.*?do\s*(.*)\s*end/m)
cache_content = $1
create_file "db/migrate/#{timestamp}_create_solid_cache_tables.rb", <<~RUBY
class CreateSolidCacheTables < ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]
def change
#{cache_content.split("\n").map { |line| " " + line }.join("\n").rstrip}
end
end
RUBY
timestamp += 1
end
end
if File.exist?("db/queue_schema.rb")
queue_schema = File.read("db/queue_schema.rb")
if queue_schema.match(/ActiveRecord::Schema.*?\.define.*?do\s*(.*)\s*end/m)
queue_content = $1
create_file "db/migrate/#{timestamp}_create_solid_queue_tables.rb", <<~RUBY
class CreateSolidQueueTables < ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]
def change
#{queue_content.split("\n").map { |line| " " + line }.join("\n").rstrip}
end
end
RUBY
timestamp += 1
end
end
if File.exist?("db/cable_schema.rb")
cable_schema = File.read("db/cable_schema.rb")
if cable_schema.match(/ActiveRecord::Schema.*?\.define.*?do\s*(.*)\s*end/m)
cable_content = $1
create_file "db/migrate/#{timestamp}_create_solid_cable_tables.rb", <<~RUBY
class CreateSolidCableTables < ActiveRecord::Migration[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]
def change
#{cable_content.split("\n").map { |line| " " + line }.join("\n").rstrip}
end
end
RUBY
end
end
# Remove the separate schema files and migration directories
remove_file "db/cache_schema.rb" if File.exist?("db/cache_schema.rb")
remove_file "db/queue_schema.rb" if File.exist?("db/queue_schema.rb")
remove_file "db/cable_schema.rb" if File.exist?("db/cable_schema.rb")
# Remove separate migration directories (Rails 8 multi-database feature)
remove_dir "db/cache_migrate" if File.directory?("db/cache_migrate")
remove_dir "db/queue_migrate" if File.directory?("db/queue_migrate")
remove_dir "db/cable_migrate" if File.directory?("db/cable_migrate")
# Run migrations to create all tables in the primary database
rails_command("db:migrate")
git add: "-A"
git commit: "-m 'Configure single database (cache/queue/cable share primary DB)'"
else
say "Keeping Rails 8 multi-database setup (separate databases for cache/queue/cable)...", :cyan
# Just run migrations - Rails 8 default multi-database setup is already configured
rails_command("db:migrate")
git add: "-A"
git commit: "-m 'Run initial migrations with Rails 8 multi-database setup'"
end
# === GENERATOR CONFIGURATION ===
generators_config = <<-HEREDOC.gsub(/^ /, "")
config.generators do |g|
g.system_tests = nil
g.scaffold_stylesheet false
end
HEREDOC
gsub_file "config/application.rb",
/config.generators.system_tests = nil/,
generators_config
git add: "-A"
git commit: "-m 'Configure generators'"
# === SOLID QUEUE DEVELOPMENT CONFIGURATION ===
# Add SolidQueue worker to Procfile.dev if it exists (for apps using bin/dev with asset compilation)
if File.exist?("Procfile.dev")
say "Adding SolidQueue worker to Procfile.dev...", :cyan
append_file "Procfile.dev", "jobs: bundle exec rake solid_queue:start\n"
# Configure development environment to use SolidQueue
inject_into_file "config/environments/development.rb",
before: "end\n" do
<<-RUBY
# Use SolidQueue for background jobs in development
# This matches production behavior and helps catch job-related issues early
config.active_job.queue_adapter = :solid_queue
RUBY
end
git add: "-A"
git commit: "-m 'Configure SolidQueue for development with Procfile.dev'"
end
# === GOLDILOADER CONFIGURATION (if enabled) ===
if performance_options[:goldiloader]
create_file "config/initializers/goldiloader.rb", <<~RUBY
# Goldiloader configuration
# Automatic eager loading to prevent N+1 queries
# Goldiloader is enabled globally by default
# You can disable it for specific code blocks:
#
# Goldiloader.disabled do
# # Code here runs without automatic eager loading
# end
#
# Or disable it for specific associations:
#
# class Post < ApplicationRecord
# has_many :comments, -> { auto_include(false) }
# end
#
# Note: Bullet's unused eager loading detection is disabled
# to avoid conflicts with Goldiloader's automatic loading
RUBY
git add: "-A"
git commit: "-m 'Configure Goldiloader for automatic N+1 prevention'"
end
# === RENDER.COM DEPLOYMENT CONFIGURATION (if selected) ===
if render_options[:enabled]
require "yaml"
say "Configuring for Render.com deployment...", :cyan
# Determine settings based on tier
web_concurrency = render_options[:free_tier] ? 0 : 2
db_plan = render_options[:free_tier] ? "free" : "starter"
service_plan = render_options[:free_tier] ? "free" : "starter"
using_supabase = render_options[:database_provider] == "supabase"
# Create bin/render-build.sh (NO db:migrate - that goes in preDeployCommand)
create_file "bin/render-build.sh", <<~BASH
#!/usr/bin/env bash
# exit on error
set -o errexit
bundle install
bundle exec rake assets:precompile
bundle exec rake assets:clean
BASH
# Make script executable
chmod "bin/render-build.sh", 0755
# Build render.yaml programmatically to avoid indentation bugs
render_config = {"services" => []}
# Only add Render Postgres if not using Supabase
unless using_supabase
render_config["databases"] = [
{
"name" => "#{app_name}-db",
"databaseName" => "#{app_name}_production",
"user" => app_name,
"plan" => db_plan
}
]
end
# Web service configuration
web_service = {
"type" => "web",
"name" => "#{app_name}-web",
"runtime" => "ruby",
"plan" => service_plan,
"buildCommand" => "./bin/render-build.sh",
"preDeployCommand" => "bundle exec rake db:migrate",
"startCommand" => "bundle exec puma -C config/puma.rb",
"healthCheckPath" => "/up",
"envVars" => []
}
# Database URL configuration depends on provider
if using_supabase
# Supabase: DATABASE_URL must be entered manually in Render dashboard
web_service["envVars"] << {"key" => "DATABASE_URL", "sync" => false}
else
# Render Postgres: auto-link to provisioned database
web_service["envVars"] << {
"key" => "DATABASE_URL",
"fromDatabase" => {
"name" => "#{app_name}-db",
"property" => "connectionString"
}
}
end
# Add remaining env vars
web_service["envVars"] << {"key" => "RAILS_MASTER_KEY", "sync" => false}
web_service["envVars"] << {"key" => "WEB_CONCURRENCY", "value" => web_concurrency.to_s}
web_service["envVars"] << {"key" => "NODE_ENV", "value" => "production"}
# Add SOLID_QUEUE_IN_PUMA env var if not using separate worker
unless render_options[:separate_worker]
web_service["envVars"] << {"key" => "SOLID_QUEUE_IN_PUMA", "value" => "true"}
end
# Add custom domain if specified
if render_options[:domain]
domains = [render_options[:domain]]
domains << "www.#{render_options[:domain]}" if render_options[:include_www]
web_service["domains"] = domains
end
render_config["services"] << web_service
# Add worker service if separate_worker is enabled
if render_options[:separate_worker]
worker_service = {
"type" => "worker",
"name" => "#{app_name}-worker",
"runtime" => "ruby",
"plan" => service_plan,
"buildCommand" => "bundle install",
"startCommand" => "bundle exec rake solid_queue:start",
"envVars" => []
}
# Database URL for worker
if using_supabase
worker_service["envVars"] << {"key" => "DATABASE_URL", "sync" => false}
else
worker_service["envVars"] << {
"key" => "DATABASE_URL",
"fromDatabase" => {
"name" => "#{app_name}-db",
"property" => "connectionString"
}
}
end
worker_service["envVars"] << {"key" => "RAILS_MASTER_KEY", "sync" => false}
render_config["services"] << worker_service
end
# Generate YAML and validate it
render_yaml_content = render_config.to_yaml
# Validate YAML before writing
begin
YAML.safe_load(render_yaml_content)
rescue Psych::SyntaxError => e
say "ERROR: Generated render.yaml is invalid: #{e.message}", :red
raise "Invalid YAML generated for render.yaml"
end
create_file "render.yaml", render_yaml_content
# Configure Puma plugin for Solid Queue if not using separate worker
unless render_options[:separate_worker]
# Check if puma.rb already has the solid_queue plugin to avoid duplication
puma_content = File.read("config/puma.rb")
unless puma_content.include?("plugin :solid_queue")
append_to_file "config/puma.rb", <<~RUBY
# Run Solid Queue in Puma process (controlled by SOLID_QUEUE_IN_PUMA env var)
# This is used for Render.com deployments without a separate worker service
plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"]
RUBY
end
# Silence polling in development
inject_into_file "config/environments/development.rb",
" # Silence Solid Queue polling logs in development\n config.solid_queue.silence_polling = true\n\n",
after: "Rails.application.configure do\n"
end
# Move esbuild to dependencies (not devDependencies) for production builds
if File.exist?("package.json")
package_json = JSON.parse(File.read("package.json"))
if package_json.dig("devDependencies", "esbuild")
esbuild_version = package_json["devDependencies"].delete("esbuild")
package_json["dependencies"] ||= {}
package_json["dependencies"]["esbuild"] = esbuild_version
File.write("package.json", JSON.pretty_generate(package_json) + "\n")
say "Moved esbuild to dependencies for production builds", :green
end
end
# Generate deployment checklist
checklist_content = <<~MARKDOWN
# Render.com Deployment Checklist for #{app_name.humanize}
## Before First Deploy
- [ ] Push code to GitHub/GitLab
- [ ] Create Render account at https://render.com
MARKDOWN
if using_supabase
checklist_content += <<~MARKDOWN
- [ ] Create Supabase account and project at https://supabase.com
- [ ] Get your database connection string (see Supabase Setup below)
MARKDOWN
end
checklist_content += <<~MARKDOWN
- [ ] Connect your repository to Render (Render will auto-detect render.yaml)
## Environment Variables (set in Render Dashboard)
The following must be set manually in the Render Dashboard:
- [ ] `RAILS_MASTER_KEY` - Copy the contents of `config/master.key`
(This file is gitignored for security - you must copy it manually)
MARKDOWN
if using_supabase
checklist_content += <<~MARKDOWN
- [ ] `DATABASE_URL` - Your Supabase connection string (see below)
MARKDOWN
end
checklist_content += <<~MARKDOWN
## After Deploy
- [ ] Verify health check passes at `/up`
- [ ] Check service logs for any errors
- [ ] Test your application functionality
MARKDOWN
if using_supabase
checklist_content += <<~MARKDOWN
## Supabase Database Setup
### 1. Create a Supabase Project
1. Go to https://supabase.com and sign in
2. Click "New Project"
3. Choose a name, password, and region (pick one close to your Render region)
4. Wait for the project to be created (~2 minutes)
### 2. Get Your Connection String
1. In your Supabase project, go to **Settings** → **Database**
2. Scroll to **Connection string** section
3. Select **URI** tab
4. Copy the connection string (it looks like):
```
postgresql://postgres.[project-ref]:[password]@aws-0-[region].pooler.supabase.com:6543/postgres
```
### 3. Choose the Right Connection Mode
Supabase offers two connection modes:
| Mode | Port | Best For |
|------|------|----------|
| **Transaction** (recommended) | 6543 | Web apps, Rails |
| Session | 5432 | Long-running connections |
**Use Transaction mode (port 6543)** for Rails applications.
### 4. Add to Render Dashboard
1. In Render, go to your web service → **Environment**
2. Add `DATABASE_URL` with your Supabase connection string
3. Replace `[YOUR-PASSWORD]` with your database password
4. If you have a worker service, add the same `DATABASE_URL` there
### Important Notes
- **Password**: Use the password you set when creating the Supabase project
- **SSL**: Supabase requires SSL, which Rails handles automatically
- **Free Tier**: Supabase free tier includes 500MB storage, no expiration
- **Pooling**: Transaction pooler is already configured in the connection string
MARKDOWN
end
if render_options[:domain]
checklist_content += <<~MARKDOWN
## Custom Domain Setup: #{render_options[:domain]}
Your render.yaml is pre-configured for `#{render_options[:domain]}`#{render_options[:include_www] ? " and `www.#{render_options[:domain]}`" : ""}.
### DNS Configuration
Add these records at your domain registrar (e.g., Namecheap, GoDaddy, Cloudflare):
| Type | Name | Value |
|------|------|-------|
| CNAME | www | #{app_name}-web.onrender.com |
| CNAME or ALIAS | @ (root) | #{app_name}-web.onrender.com |
**Note:** Some registrars don't support CNAME/ALIAS for root domains.
Check Render's docs for alternative A record configuration.
### After DNS Configuration
- [ ] Wait for DNS propagation (can take up to 48 hours, usually faster)
- [ ] Verify SSL certificate is automatically provisioned by Render
- [ ] Test both root domain and www (if configured)
MARKDOWN
end
db_provider_display = using_supabase ? "Supabase (external)" : "Render Postgres (#{db_plan})"
checklist_content += <<~MARKDOWN
## Configuration Summary
| Setting | Value |
|---------|-------|
| Tier | #{render_options[:free_tier] ? "Free" : "Paid"} |
| Database | #{db_provider_display} |
| WEB_CONCURRENCY | #{web_concurrency} #{render_options[:free_tier] ? "(single process, threaded - optimized for 512MB)" : "(multiple workers)"} |
| Background Jobs | #{render_options[:separate_worker] ? "Separate worker service" : "Puma plugin (in web process)"} |
#{render_options[:domain] ? "| Custom Domain | #{render_options[:domain]} |" : ""}
## Useful Commands
```bash
# View logs
render logs --service #{app_name}-web
# SSH into service (paid plans only)
render ssh --service #{app_name}-web
# Restart service
render restart --service #{app_name}-web
```
## Troubleshooting
### Build Failures
- Check that all gems install correctly
- Verify Node.js version compatibility
- Check asset compilation logs
### Migration Failures
- Migrations run in preDeployCommand (after build, before start)
- Check DATABASE_URL is correctly set
- Verify database is accessible from web service
### Memory Issues (Free Tier)
- Free tier has 512MB RAM limit
- WEB_CONCURRENCY=0 uses single process with threads
- Monitor memory usage in Render dashboard
- Consider upgrading to paid tier for production workloads
## Documentation
- [Render Rails Deployment Guide](https://render.com/docs/deploy-rails)
- [Render Blueprint Spec](https://render.com/docs/blueprint-spec)
- [Custom Domains on Render](https://render.com/docs/custom-domains)
MARKDOWN
create_file "RENDER_DEPLOYMENT.md", checklist_content
git add: "-A"
git commit: "-m 'Configure Render.com deployment with #{render_options[:separate_worker] ? 'separate worker service' : 'Puma plugin'}'"
end
# === GITHUB ACTIONS CI CONFIGURATION ===
if ci_options[:github_actions]
say "Configuring GitHub Actions CI...", :cyan
create_file ".github/workflows/ci.yml", <<~YAML
name: CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:18
ports:
- 5432:5432