What is the best way to handle dynamic content_type in Sinatra

Posted by lusis on Stack Overflow See other posts from Stack Overflow or by lusis
Published on 2010-05-24T15:06:50Z Indexed on 2010/05/24 15:11 UTC
Read the original article Hit count: 157

Filed under:
|

I'm currently doing the following but it feels "kludgy":

module Sinatra
    module DynFormat
        def 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.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about sinatra