|
35 | 35 | end |
36 | 36 | end |
37 | 37 |
|
| 38 | + context 'with a :merge option' do |
| 39 | + let(:nested_hash) do |
| 40 | + { something: { like_nested_hash: true }, special: { like_nested_hash: '12' } } |
| 41 | + end |
| 42 | + |
| 43 | + it 'merges an exposure to the root' do |
| 44 | + subject.expose(:something, merge: true) |
| 45 | + expect(subject.represent(nested_hash).serializable_hash).to eq(nested_hash[:something]) |
| 46 | + end |
| 47 | + |
| 48 | + it 'allows to solve collisions providing a lambda to a :merge option' do |
| 49 | + subject.expose(:something, merge: true) |
| 50 | + subject.expose(:special, merge: ->(_, v1, v2) { v1 && v2 ? 'brand new val' : v2 }) |
| 51 | + expect(subject.represent(nested_hash).serializable_hash).to eq(like_nested_hash: 'brand new val') |
| 52 | + end |
| 53 | + end |
| 54 | + |
38 | 55 | context 'with a block' do |
39 | 56 | it 'errors out if called with multiple attributes' do |
40 | 57 | expect { subject.expose(:name, :email) { true } }.to raise_error ArgumentError |
@@ -243,6 +260,30 @@ class Parent < Person |
243 | 260 | } |
244 | 261 | ) |
245 | 262 | end |
| 263 | + it 'merges attriutes if :merge option is passed' do |
| 264 | + user_entity = Class.new(Grape::Entity) |
| 265 | + admin_entity = Class.new(Grape::Entity) |
| 266 | + user_entity.expose(:id, :name) |
| 267 | + admin_entity.expose(:id, :name) |
| 268 | + |
| 269 | + subject.expose(:profiles) do |
| 270 | + subject.expose(:users, merge: true, using: user_entity) |
| 271 | + subject.expose(:admins, merge: true, using: admin_entity) |
| 272 | + end |
| 273 | + |
| 274 | + subject.expose :awesome do |
| 275 | + subject.expose(:nested, merge: true) { |_| { just_a_key: 'value' } } |
| 276 | + subject.expose(:another_nested, merge: true) { |_| { just_another_key: 'value' } } |
| 277 | + end |
| 278 | + |
| 279 | + additional_hash = { users: [{ id: 1, name: 'John' }, { id: 2, name: 'Jay' }], |
| 280 | + admins: [{ id: 3, name: 'Jack' }, { id: 4, name: 'James' }] |
| 281 | + } |
| 282 | + expect(subject.represent(additional_hash).serializable_hash).to eq( |
| 283 | + profiles: additional_hash[:users] + additional_hash[:admins], |
| 284 | + awesome: { just_a_key: 'value', just_another_key: 'value' } |
| 285 | + ) |
| 286 | + end |
246 | 287 | end |
247 | 288 | end |
248 | 289 |
|
@@ -863,7 +904,7 @@ class Parent < Person |
863 | 904 | subject.expose :my_items |
864 | 905 |
|
865 | 906 | representation = subject.represent(4.times.map { Object.new }, serializable: true) |
866 | | - expect(representation).to be_kind_of(Hash) |
| 907 | + expect(representation).to be_kind_of(Grape::Entity::Exposure::NestingExposure::OutputBuilder) |
867 | 908 | expect(representation).to have_key :my_items |
868 | 909 | expect(representation[:my_items]).to be_kind_of Array |
869 | 910 | expect(representation[:my_items].size).to be 4 |
|
0 commit comments