What is the best way to handle dynamic content_type in Sinatra
I'm currently doing the following but it feels "kludgy":
module Sinatra
module DynFormat
d开发者_StackOverflowef dform(data,ct)
if ct == 'xml';return data.to_xml;end
if ct == 'json';return data.to_json;end
end
end
helpers DynFormat
end
My goal is to plan ahead. Right now we're only working with XML for this particular web service but we want to move over to JSON as soon as all the components in our stack support it.
Here's a sample route:
get '/api/people/named/:name/:format' do
format = params[:format]
h = {'xml' => 'text/xml','json' => 'application/json'}
content_type h[format], :charset => 'utf-8'
person = params[:name]
salesperson = Salespeople.find(:all, :conditions => ['name LIKE ?', "%#{person}%"])
"#{dform(salesperson,format)}"
end
It just feels like I'm not doing it the best way possible.
a few cleanups in the helper:
- adding case statement
- adding a default value for format
- the helper now sets the content type
code:
module Sinatra
module DynFormat
CONTENT_TYPES={'xml' => 'text/xml','json' => 'application/json'}
def dform(data,format=params[:format])
content_type CONTENT_TYPES[format], :charset => 'utf-8'
case format
when 'xml'
data.to_xml
when 'json'
data.to_json
end
end
end
helpers DynFormat
end
here I factored out the content type handling, and removed the person temp variable since it is only used once in favor of using params. code:
get '/api/people/named/:name/:format' do
salesperson = Salespeople.find(:all, :conditions => ['name LIKE ?', "%#{params[:name]}%"])
dform(salesperson)
end
Make sense, look cool?
精彩评论