Skip to content

Commit

Permalink
Merge pull request #1956 from Shopify/uk-short-circuit-rails-lookalikes
Browse files Browse the repository at this point in the history
Short circuit Rails app loading if Rails constant isn't defined
  • Loading branch information
paracycle authored Jul 11, 2024
2 parents df5079f + 2be6bbb commit b3cec5b
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
19 changes: 15 additions & 4 deletions lib/tapioca/loaders/loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,23 @@ def load_bundle(gemfile, initialize_file, require_file, halt_upon_load_error)
).void
end
def load_rails_application(environment_load: false, eager_load: false, app_root: ".", halt_upon_load_error: true)
return unless File.exist?("#{app_root}/config/application.rb")
return unless File.exist?(File.expand_path("config/application.rb", app_root))

if environment_load
require "./#{app_root}/config/environment"
load_path = if environment_load
"config/environment"
else
require "./#{app_root}/config/application"
"config/application"
end

require File.expand_path(load_path, app_root)

unless defined?(Rails)
say(
"\nTried to load the app from `#{load_path}` as a Rails application " \
"but the `Rails` constant wasn't defined after loading the file.",
:yellow,
)
return
end

eager_load_rails_app if eager_load
Expand Down
50 changes: 50 additions & 0 deletions spec/tapioca/cli/dsl_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2801,6 +2801,56 @@ class PostCompiler < Tapioca::Dsl::Compiler
end
end

describe "rails-like-applications" do
before(:all) do
@project.write!("config/environment.rb", <<~RB)
require_relative "application.rb"
RB

@project.write!("config/application.rb", <<~RB)
# Don't define any constant named `Rails`.
require "smart_properties"
class Post
include SmartProperties
property :title, accepts: String
end
RB

@project.require_real_gem("smart_properties", "1.15.0")
@project.bundle_install!
end

after(:all) do
@project.remove!("config/application.rb")
end

it "shows a warning about the Rails constant not having been loaded" do
res = @project.tapioca("dsl")

assert_stdout_equals(<<~OUT, res)
Loading DSL extension classes... Done
Loading Rails application...\u0020
Tried to load the app from `config/environment` as a Rails application but the `Rails` constant wasn't defined after loading the file.
Done
Loading DSL compiler classes... Done
Compiling DSL RBI files...
create sorbet/rbi/dsl/post.rbi
Done
Checking generated RBI files... Done
No errors found
All operations performed in working directory.
Please review changes and commit them.
OUT
assert_empty_stderr(res)
assert_success_status(res)
end
end

describe "halt-upon-load-error" do
before(:all) do
@project.write!("config/environment.rb", <<~RB)
Expand Down

0 comments on commit b3cec5b

Please sign in to comment.