Skip to content

Commit f1401eb

Browse files
author
Robert Ross
committed
Add ability to use lambdas with format_with options.
1 parent 209e1db commit f1401eb

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

lib/grape/entity.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,11 @@ def value_for(attribute, options = {})
203203
elsif exposure_options[:using]
204204
exposure_options[:using].represent(object.send(attribute), :root => nil)
205205
elsif exposure_options[:format_with]
206-
self.send(exposure_options[:format_with].to_sym, object.send(attribute))
206+
if exposure_options[:format_with].is_a? Symbol
207+
self.send(exposure_options[:format_with].to_sym, object.send(attribute))
208+
elsif exposure_options[:format_with].respond_to? :call
209+
exposure_options[:format_with].call(object.send(attribute))
210+
end
207211
else
208212
object.send(attribute)
209213
end

spec/grape/entity_spec.rb

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -204,9 +204,10 @@
204204
:name => 'Bob Bobson',
205205
:email => '[email protected]',
206206
:birthday => Time.new(2012, 2, 27),
207+
:fantasies => ['Unicorns', 'Double Rainbows', 'Nessy'],
207208
:friends => [
208-
mock(:name => "Friend 1", :email => '[email protected]', :birthday => Time.new(2012, 2, 27), :friends => []),
209-
mock(:name => "Friend 2", :email => '[email protected]', :birthday => Time.new(2012, 2, 27), :friends => [])
209+
mock(:name => "Friend 1", :email => '[email protected]', :fantasies => [], :birthday => Time.new(2012, 2, 27), :friends => []),
210+
mock(:name => "Friend 2", :email => '[email protected]', :fantasies => [], :birthday => Time.new(2012, 2, 27), :friends => [])
210211
]
211212
} }
212213
subject{ fresh_class.new(model) }
@@ -236,6 +237,8 @@
236237
def timestamp(date)
237238
date.strftime('%m/%d/%Y')
238239
end
240+
241+
expose :fantasies, :format_with => lambda {|f| f.reverse }
239242
end
240243
end
241244

@@ -272,6 +275,10 @@ class FriendEntity < Grape::Entity
272275
it 'should return a formatted value if format_with is passed' do
273276
subject.send(:value_for, :birthday).should == '02/27/2012'
274277
end
278+
279+
it 'should return a formatted value if format_with is passed a lambda' do
280+
subject.send(:value_for, :fantasies).should == ['Nessy', 'Double Rainbows', 'Unicorns']
281+
end
275282
end
276283

277284
describe '#key_for' do

0 commit comments

Comments
 (0)