Skip to content

Commit d65df18

Browse files
alanjcfsdblock
authored andcommitted
Add fetch method to fetch from opts_hash (#226)
Add a line to CHANGELOG about fetch method Add specs for `#fetch` `#fetch` will pass the method to the option hash.
1 parent 8f5b029 commit d65df18

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
* [#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).
55
* [#219](https://github.com/ruby-grape/grape-entity/pull/219): Fix: double pass options in serializable_hash - [@sbatykov](https://github.com/sbatykov).
6+
* [#226](https://github.com/ruby-grape/grape-entity/pull/226): Add fetch method to fetch from opts_hash - [@alanjcfs](https://github.com/alanjcfs).
67
* Your contribution here.
78

89
0.5.1 (2016-4-4)

lib/grape_entity/options.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ def [](key)
1515
@opts_hash[key]
1616
end
1717

18+
def fetch(*args)
19+
@opts_hash.fetch(*args)
20+
end
21+
1822
def key?(key)
1923
@opts_hash.key? key
2024
end

spec/grape_entity/entity_spec.rb

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1729,5 +1729,39 @@ class UserEntity < Grape::Entity
17291729
end
17301730
end
17311731
end
1732+
1733+
describe Grape::Entity::Options do
1734+
module EntitySpec
1735+
class Crystalline
1736+
attr_accessor :prop1, :prop2
1737+
1738+
def initialize
1739+
@prop1 = 'value1'
1740+
@prop2 = 'value2'
1741+
end
1742+
end
1743+
1744+
class CrystallineEntity < Grape::Entity
1745+
expose :prop1, if: ->(_, options) { options.fetch(:signal) }
1746+
expose :prop2, if: ->(_, options) { options.fetch(:beam, 'destructive') == 'destructive' }
1747+
end
1748+
end
1749+
1750+
context '#fetch' do
1751+
it 'without passing in a required option raises KeyError' do
1752+
expect { EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new).as_json }.to raise_error KeyError
1753+
end
1754+
1755+
it 'passing in a required option will expose the values' do
1756+
crystalline_entity = EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new, signal: true)
1757+
expect(crystalline_entity.as_json).to eq(prop1: 'value1', prop2: 'value2')
1758+
end
1759+
1760+
it 'with an option that is not default will not expose that value' do
1761+
crystalline_entity = EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new, signal: true, beam: 'intermittent')
1762+
expect(crystalline_entity.as_json).to eq(prop1: 'value1')
1763+
end
1764+
end
1765+
end
17321766
end
17331767
end

0 commit comments

Comments
 (0)