tags:

views:

217

answers:

1

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.

+1  A: 

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?

BaroqueBobcat
That's exactly what I was looking for. I wasn't aware that params were made available to helpers. I'm still new to sinatra in that regard. I'm still not keen on having to call the helper each time but that will cut out quite a bit of the repetition. I think I have an idea to automatically apply the helper now thanks to you.I'll give it a shot.
lusis