Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/active_resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ module ActiveResource
autoload :HttpMock
autoload :Schema
autoload :Singleton
autoload :InheritingHash
autoload :Validations
autoload :Collection
end
Expand Down
11 changes: 5 additions & 6 deletions lib/active_resource/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -697,12 +697,11 @@ def connection(refresh = false)
end

def headers
headers_state = self._headers || {}
if superclass != Object
self._headers = superclass.headers.merge(headers_state)
else
headers_state
end
self._headers ||= if superclass != Object
InheritingHash.new(superclass.headers)
else
{}
end
end

attr_writer :element_name
Expand Down
15 changes: 15 additions & 0 deletions lib/active_resource/inheriting_hash.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

module ActiveResource
class InheritingHash < Hash
def initialize(parent_hash = {})
# Default hash value must be nil, which allows fallback lookup on parent hash
super(nil)
@parent_hash = parent_hash
end

def [](key)
super || @parent_hash[key]
end
end
end
26 changes: 26 additions & 0 deletions test/cases/base_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -706,6 +706,32 @@ def test_header_inheritance_should_not_leak_upstream
assert_nil fruit.headers["key2"]
end

def test_header_inheritance_can_override_upstream
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = "http://market"

fruit.headers["key"] = "fruit-value"
assert_equal "fruit-value", apple.headers["key"]

apple.headers["key"] = "apple-value"
assert_equal "apple-value", apple.headers["key"]
assert_equal "fruit-value", fruit.headers["key"]
end


def test_header_inheritance_should_not_override_upstream_on_read
fruit = Class.new(ActiveResource::Base)
apple = Class.new(fruit)
fruit.site = "http://market"

fruit.headers["key"] = "value"
assert_equal "value", apple.headers["key"]

fruit.headers["key"] = "new-value"
assert_equal "new-value", apple.headers["key"]
end

def test_header_should_be_copied_to_main_thread_if_not_defined
fruit = Class.new(ActiveResource::Base)

Expand Down