Skip to content

Commit 028e905

Browse files
committed
Add Entity.[] for Grape >= 3.2 param type compatibility
Grape 3.2 requires all param types to respond to [] for coercion. Entity classes used as param types (e.g. `type: UserEntity`) crash at route definition time because Grape::DryTypes checks respond_to?(:[]) and raises ArgumentError when it is missing. Add a pass-through [] class method that satisfies the check without altering any existing behavior.
1 parent 99c2ffe commit 028e905

2 files changed

Lines changed: 22 additions & 0 deletions

File tree

lib/grape_entity/entity.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,12 @@ def hash_access=(value)
129129
def delegation_opts
130130
@delegation_opts ||= { hash_access: hash_access }
131131
end
132+
133+
# Satisfies the respond_to?(:[]) check in Grape::DryTypes (>= 3.2)
134+
# so Entity subclasses can be used as param types.
135+
def [](val)
136+
val
137+
end
132138
end
133139

134140
@formatters = {}

spec/grape_entity/entity_spec.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,6 +1010,22 @@ class Parent < Person
10101010
end
10111011
end
10121012

1013+
describe '.[]' do
1014+
it 'returns the input unchanged' do
1015+
hash = { name: 'Test' }
1016+
expect(subject[hash]).to eq(hash)
1017+
end
1018+
1019+
it 'returns nil unchanged' do
1020+
expect(subject[nil]).to be_nil
1021+
end
1022+
1023+
it 'is inherited by subclasses' do
1024+
subclass = Class.new(subject)
1025+
expect(subclass[{ id: 1 }]).to eq(id: 1)
1026+
end
1027+
end
1028+
10131029
describe '.represent' do
10141030
it 'returns a single entity if called with one object' do
10151031
expect(subject.represent(Object.new)).to be_kind_of(subject)

0 commit comments

Comments
 (0)