Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib/grape/middleware/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ module Formats
FORMATTERS = {
:json => :encode_json,
:txt => :encode_txt,
:xml => :encode_xml
}
PARSERS = {
:json => :decode_json
Expand Down Expand Up @@ -120,6 +121,10 @@ def encode_json(object)
def encode_txt(object)
object.respond_to?(:to_txt) ? object.to_txt : object.to_s
end

def encode_xml(object)
object.respond_to?(:to_xml) ? object.to_xml : object.to_s
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't you want encode_xml to always return XML, much like JSON to decrease the burden on the client? For example ... in the case where the object doesn't self-convert to XML?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but I'm not sure about adding a dependency to fall back to for xml serialization like multi_json does for json, or if I'm missing how to serialize with the current dependencies.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll merge this, but it would be nice to get a follow-up. You can add another dependency if it makes sense.

end
end

end
Expand Down
11 changes: 11 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,17 @@ def serializable_hash

subject.call({'PATH_INFO' => '/somewhere'}).last.each{|b| b.should == '{"abc":"def"}'}
end

it 'should call #to_xml if the content type is xml' do
@body = "string"
@body.instance_eval do
def to_xml
"<bar/>"
end
end

subject.call({'PATH_INFO' => '/somewhere.xml'}).last.each{|b| b.should == '<bar/>'}
end
end

context 'detection' do
Expand Down