diff --git a/CHANGELOG.md b/CHANGELOG.md index ee3680c..f9ee186 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ * [#298](https://github.com/codegram/hyperclient/pull/300): Upgraded RuboCop to 1.80.2 - [@dblock](https://github.com/dblock). * [#298](https://github.com/codegram/hyperclient/pull/298): Upgraded RuboCop to 1.63.5 - [@dblock](https://github.com/dblock). +* [#319](https://github.com/codegram/hyperclient/pull/319): Fixed `Resource#to_h` returning `nil` instead of the same result as `#to_hash` - [@dblock](https://github.com/dblock). * [#320](https://github.com/codegram/hyperclient/pull/320): Documented how to handle non-`hal+json` responses via the Faraday response middleware's `content_type` matcher - [@dblock](https://github.com/dblock). * [#321](https://github.com/codegram/hyperclient/pull/321): Added Ruby 4.0 to the CI test matrix - [@dblock](https://github.com/dblock). * Your contribution here. diff --git a/lib/hyperclient/resource.rb b/lib/hyperclient/resource.rb index d953e85..c11cee9 100644 --- a/lib/hyperclient/resource.rb +++ b/lib/hyperclient/resource.rb @@ -66,6 +66,18 @@ def [](name) send(name) if respond_to?(name) end + # Public: Returns the attributes of the Resource as a Hash. + # + # Delegates explicitly (rather than relying on method_missing) since + # Array also defines #to_h (but not #to_hash), which meant the + # `Array.method_defined?(method)` guard in method_missing let #to_hash + # through but silently swallowed #to_h, returning nil instead of the + # attributes hash. + def to_h + _attributes.to_h + end + alias to_hash to_h + def fetch(key, *args) return self[key] if respond_to?(key) diff --git a/test/hyperclient/collection_test.rb b/test/hyperclient/collection_test.rb index 1b29066..9315dd4 100644 --- a/test/hyperclient/collection_test.rb +++ b/test/hyperclient/collection_test.rb @@ -41,6 +41,16 @@ module Hyperclient end end + describe '#to_h' do + it 'returns the wrapped collection as a hash' do + _(collection.to_h).must_be_kind_of Hash + end + + it 'returns the same result as #to_hash' do + _(collection.to_h).must_equal(collection.to_hash) + end + end + describe '#to_s' do it 'returns the wrapped collection as a hash' do _(collection.to_s).must_be_kind_of Hash diff --git a/test/hyperclient/resource_test.rb b/test/hyperclient/resource_test.rb index a566119..228d98f 100644 --- a/test/hyperclient/resource_test.rb +++ b/test/hyperclient/resource_test.rb @@ -239,5 +239,19 @@ module Hyperclient _(resource.inspect).must_include 'attributes:' end end + + describe '#to_h and #to_hash' do + let(:resource) do + Resource.new({ '_links' => {}, 'title' => 'Order', 'total' => 42 }, entry_point) + end + + it 'returns the attributes as a Hash from #to_hash' do + _(resource.to_hash).must_equal('title' => 'Order', 'total' => 42) + end + + it 'returns the same result from #to_h as #to_hash' do + _(resource.to_h).must_equal(resource.to_hash) + end + end end end