Skip to content

Commit 52a2851

Browse files
robertoz-01LeFnord
authored andcommitted
Allow exposures to call methods defined in included modules (#307)
* Allow exposures to call methods defined in included modules * Fix #258 * Update Changelog with the Pull Request link
1 parent 55383e5 commit 52a2851

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
#### Fixes
99

1010
* Your contribution here.
11+
* [#258](https://github.com/ruby-grape/grape-entity/pull/307): Allow exposures to call methods defined in modules included in an entity [@robertoz-01](https://github.com/robertoz-01).
1112

1213
### 0.7.1 (2018-01-30)
1314

lib/grape_entity/entity.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -506,13 +506,20 @@ def value_for(key, options = Options.new)
506506
end
507507

508508
def delegate_attribute(attribute)
509-
if respond_to?(attribute, true) && Grape::Entity > method(attribute).owner
509+
if is_defined_in_entity?(attribute)
510510
send(attribute)
511511
else
512512
delegator.delegate(attribute)
513513
end
514514
end
515515

516+
def is_defined_in_entity?(attribute)
517+
return false unless respond_to?(attribute, true)
518+
519+
ancestors = self.class.ancestors
520+
ancestors.index(Grape::Entity) > ancestors.index(method(attribute).owner)
521+
end
522+
516523
alias as_json serializable_hash
517524

518525
def to_json(options = {})

spec/grape_entity/entity_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1376,6 +1376,18 @@ class TestEntity < Grape::Entity
13761376
expect(res).to have_key :nonexistent_attribute
13771377
end
13781378

1379+
it "exposes attributes defined through module inclusion" do
1380+
module SharedAttributes
1381+
def a_value
1382+
3.14
1383+
end
1384+
end
1385+
fresh_class.include(SharedAttributes)
1386+
fresh_class.expose :a_value
1387+
res = fresh_class.new(model).serializable_hash
1388+
expect(res[:a_value]).to eq(3.14)
1389+
end
1390+
13791391
it 'does not expose attributes that are generated by a block but have not passed criteria' do
13801392
fresh_class.expose :nonexistent_attribute,
13811393
proc: ->(_, _) { 'I exist, but it is not yet my time to shine' },

0 commit comments

Comments
 (0)