Skip to content

Commit

Permalink
Add fetch method to fetch from opts_hash
Browse files Browse the repository at this point in the history
Add a line to CHANGELOG about fetch method

Add specs for `#fetch`

`#fetch` will pass the method to the option hash.
  • Loading branch information
alanjcfs committed Jun 24, 2016
1 parent 8f5b029 commit c42f4b6
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions lib/grape_entity/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
34 changes: 34 additions & 0 deletions spec/grape_entity/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit c42f4b6

Please sign in to comment.