diff --git a/CHANGELOG.md b/CHANGELOG.md index ac3ccd5d..675e2373 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ * [#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): Add fetch method to fetch from opts_hash - [@alanjcfs](https://github.com/alanjcfs). * Your contribution here. 0.5.1 (2016-4-4) diff --git a/lib/grape_entity/options.rb b/lib/grape_entity/options.rb index af91f93b..7d916efa 100644 --- a/lib/grape_entity/options.rb +++ b/lib/grape_entity/options.rb @@ -15,6 +15,10 @@ def [](key) @opts_hash[key] end + def fetch(*args) + @opts_hash.fetch(*args) + end + def key?(key) @opts_hash.key? key end diff --git a/spec/grape_entity/entity_spec.rb b/spec/grape_entity/entity_spec.rb index b6a98f36..c0daa476 100644 --- a/spec/grape_entity/entity_spec.rb +++ b/spec/grape_entity/entity_spec.rb @@ -1729,5 +1729,39 @@ class UserEntity < Grape::Entity end end end + + describe Grape::Entity::Options do + module EntitySpec + class Crystalline + attr_accessor :prop1, :prop2 + + def initialize + @prop1 = 'value1' + @prop2 = 'value2' + end + end + + class CrystallineEntity < Grape::Entity + expose :prop1, if: ->(_, options) { options.fetch(:signal) } + expose :prop2, if: ->(_, options) { options.fetch(:beam, 'destructive') == 'destructive' } + end + end + + context '#fetch' do + it 'without passing in a required option raises KeyError' do + expect { EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new).as_json }.to raise_error KeyError + end + + it 'passing in a required option will expose the values' do + crystalline_entity = EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new, signal: true) + expect(crystalline_entity.as_json).to eq(prop1: 'value1', prop2: 'value2') + end + + it 'with an option that is not default will not expose that value' do + crystalline_entity = EntitySpec::CrystallineEntity.represent(EntitySpec::Crystalline.new, signal: true, beam: 'intermittent') + expect(crystalline_entity.as_json).to eq(prop1: 'value1') + end + end + end end end