Skip to content

Commit

Permalink
Support magic comments in .ru files
Browse files Browse the repository at this point in the history
* Such as # frozen_string_literal: true.
  • Loading branch information
eregon authored and ioquatix committed Feb 2, 2020
1 parent f2d2df4 commit e3fd0c4
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
7 changes: 5 additions & 2 deletions lib/rack/builder.rb
Expand Up @@ -109,8 +109,11 @@ def self.load_file(path, opts = Server::Options.new)
# Evaluate the given +builder_script+ string in the context of
# a Rack::Builder block, returning a Rack application.
def self.new_from_string(builder_script, file = "(rackup)")
eval "Rack::Builder.new {\n" + builder_script + "\n}.to_app",
TOPLEVEL_BINDING, file, 0
# We want to build a variant of TOPLEVEL_BINDING with self as a Rack::Builder instance.
# We cannot use instance_eval(String) as that would resolve constants differently.
binding, builder = TOPLEVEL_BINDING.eval('Rack::Builder.new.instance_eval { [binding, self] }')
eval builder_script, binding, file
builder.to_app
end

# Initialize a new Rack::Builder instance. +default_app+ specifies the
Expand Down
7 changes: 7 additions & 0 deletions test/builder/frozen.ru
@@ -0,0 +1,7 @@
# frozen_string_literal: true

run lambda { |env|
body = 'frozen'
raise "Not frozen!" unless body.frozen?
[200, { 'Content-Type' => 'text/plain' }, [body]]
}
9 changes: 9 additions & 0 deletions test/spec_builder.rb
Expand Up @@ -270,6 +270,15 @@ def config_file(name)
Encoding.default_external = enc
end
end

it "respects the frozen_string_literal magic comment" do
app, _ = Rack::Builder.parse_file(config_file('frozen.ru'))
response = Rack::MockRequest.new(app).get('/')
response.body.must_equal 'frozen'
body = response.instance_variable_get(:@body)
body.must_equal(['frozen'])
body[0].frozen?.must_equal true
end
end

describe 'new_from_string' do
Expand Down

0 comments on commit e3fd0c4

Please sign in to comment.