Skip to content

Commit

Permalink
Allow methods from ancestors of the entity
Browse files Browse the repository at this point in the history
  • Loading branch information
antmanj-visma committed Sep 8, 2016
1 parent 38e36d0 commit c058fce
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .rubocop_todo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Metrics/AbcSize:
# Offense count: 2
# Configuration parameters: CountComments.
Metrics/ClassLength:
Max: 202
Max: 206

# Offense count: 3
Metrics/CyclomaticComplexity:
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
0.5.2 (Next)
============

* [#238](https://github.com/ruby-grape/grape-entity/pull/238): `#delegate_attribute` delegates to methods included from inherited entities - [@anakinj](https://github.com/anakinj).
* [#215](https://github.com/ruby-grape/grape-entity/pull/217): Fix: `#delegate_attribute` no longer delegates to methods included with `Kernel` - [@maltoe](https://github.com/maltoe).
* [#219](https://github.com/ruby-grape/grape-entity/pull/219): Fix: double pass options in serializable_hash - [@sbatykov](https://github.com/sbatykov).
* [#226](https://github.com/ruby-grape/grape-entity/pull/226): Added fetch method to fetch from opts_hash - [@alanjcfs](https://github.com/alanjcfs).
Expand Down
7 changes: 6 additions & 1 deletion lib/grape_entity/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -478,13 +478,18 @@ def value_for(key, options = Options.new)
end

def delegate_attribute(attribute)
if respond_to?(attribute, true) && method(attribute).owner == self.class
if respond_to?(attribute, true) && entity_method?(attribute)
send(attribute)
else
delegator.delegate(attribute)
end
end

def entity_method?(attribute)
method_owner = method(attribute).owner
self.class == method_owner || self.class.ancestors[0..self.class.ancestors.find_index(Grape::Entity) - 1].include?(method_owner)
end

alias_method :as_json, :serializable_hash

def to_json(options = {})
Expand Down
20 changes: 20 additions & 0 deletions spec/grape_entity/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1561,6 +1561,26 @@ class DelegatingEntity < Grape::Entity
expect(rep.value_for(:system)).to eq 'System'
end

it 'allows methods to be inherited' do
module EntitySpec
class ParentEntity < Grape::Entity
expose :parent

private

def parent
'I am the parent'
end
end

class ChildEntity < ParentEntity; end
end

foo = double('Foo', value: 'test')
rep = EntitySpec::ChildEntity.new foo
expect(rep.value_for(:parent)).to eq 'I am the parent'
end

context 'using' do
before do
module EntitySpec
Expand Down

0 comments on commit c058fce

Please sign in to comment.