Skip to content

Commit 209e1db

Browse files
author
Robert Ross
committed
Add format_with option to exposures + spec.
1 parent 31436a5 commit 209e1db

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

lib/grape/entity.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,8 @@ def value_for(attribute, options = {})
202202
exposure_options[:proc].call(object, options)
203203
elsif exposure_options[:using]
204204
exposure_options[:using].represent(object.send(attribute), :root => nil)
205+
elsif exposure_options[:format_with]
206+
self.send(exposure_options[:format_with].to_sym, object.send(attribute))
205207
else
206208
object.send(attribute)
207209
end

spec/grape/entity_spec.rb

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -201,11 +201,12 @@
201201
context 'instance methods' do
202202
let(:model){ mock(attributes) }
203203
let(:attributes){ {
204-
:name => 'Bob Bobson',
204+
:name => 'Bob Bobson',
205205
:email => '[email protected]',
206+
:birthday => Time.new(2012, 2, 27),
206207
:friends => [
207-
mock(:name => "Friend 1", :email => '[email protected]', :friends => []),
208-
mock(:name => "Friend 2", :email => '[email protected]', :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 => [])
209210
]
210211
} }
211212
subject{ fresh_class.new(model) }
@@ -229,6 +230,12 @@
229230
expose :computed do |object, options|
230231
options[:awesome]
231232
end
233+
234+
expose :birthday, :format_with => :timestamp
235+
236+
def timestamp(date)
237+
date.strftime('%m/%d/%Y')
238+
end
232239
end
233240
end
234241

@@ -261,6 +268,10 @@ class FriendEntity < Grape::Entity
261268
it 'should call through to the proc if there is one' do
262269
subject.send(:value_for, :computed, :awesome => 123).should == 123
263270
end
271+
272+
it 'should return a formatted value if format_with is passed' do
273+
subject.send(:value_for, :birthday).should == '02/27/2012'
274+
end
264275
end
265276

266277
describe '#key_for' do

0 commit comments

Comments
 (0)