Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Respect content type set in superclass before filter #1649

Merged
merged 1 commit into from Oct 18, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 6 additions & 5 deletions lib/sinatra/base.rb
Expand Up @@ -934,6 +934,7 @@ def call!(env) # :nodoc:
@params = IndifferentHash.new
@request = Request.new(env)
@response = Response.new
@pinned_response = nil
template_cache.clear if settings.reload_templates

invoke { dispatch! }
Expand Down Expand Up @@ -994,19 +995,19 @@ def forward

# Run filters defined on the class and all superclasses.
# Accepts an optional block to call after each filter is applied.
def filter!(type, base = settings)
filter! type, base.superclass if base.superclass.respond_to?(:filters)
def filter!(type, base = settings, &block)
filter!(type, base.superclass, &block) if base.superclass.respond_to?(:filters)
base.filters[type].each do |args|
result = process_route(*args)
yield result if block_given?
block.call(result) if block_given?
end
end

# Run routes defined on the class and all superclasses.
def route!(base = settings, pass_block = nil)
if routes = base.routes[@request.request_method]
routes.each do |pattern, conditions, block|
@response.delete_header('Content-Type') unless @pinned_response
response.delete_header('Content-Type') unless @pinned_response

returned_pass_block = process_route(pattern, conditions) do |*args|
env['sinatra.route'] = "#{@request.request_method} #{pattern}"
Expand Down Expand Up @@ -1124,7 +1125,7 @@ def dispatch!
invoke do
static! if settings.static? && (request.get? || request.head?)
filter! :before do
@pinned_response = !@response['Content-Type'].nil?
@pinned_response = !response['Content-Type'].nil?
end
route!
end
Expand Down
11 changes: 11 additions & 0 deletions test/filter_test.rb
Expand Up @@ -262,6 +262,17 @@ class AfterFilterTest < Minitest::Test
assert_equal 8, count
end

it "respects content type set in superclass filter" do
base = Class.new(Sinatra::Base)
base.before { content_type :json }
mock_app(base) do
get('/foo'){ {foo: :bar}.to_json }
end

get '/foo'
assert_equal 'application/json', response.headers['Content-Type']
end

it 'does not run after filter when serving static files' do
ran_filter = false
mock_app do
Expand Down