1 2 3 4 5 6 7 8 9 10
get '/:id' do @vent = Vent.get(params[:id]) erb :show end # show post get '/:id.xml' do @vent = Vent.get(params[:id]) builder :show end
Refactorings
No refactoring yet !
Adam
December 11, 2008, December 11, 2008 16:44, permalink
I'm not sure I actually like it, but...
1 2 3 4 5 6
{ '/:id' => :erb, '/:id.xml' => :builder }.each do |action,method|
get(action) do
@vent = Vent.get(params[:id])
send(method, :show)
end
end
Jason Calleiro
December 11, 2008, December 11, 2008 16:52, permalink
Thanks! the code below was recommended in a google group to me, let me know what you think. im learning all this as i go so just want to get opinions and thoughts on everything.
1 2 3 4 5 6 7 8 9
get '/:id.?:format?' do @vent = Vent.get(params[:id]) case params[:format] when 'xml' builder :show else erb :show, :layout => false end end
Tj Holowaychuk
December 16, 2008, December 16, 2008 23:44, permalink
Personally I like your first example better with them being separated, makes things more clear IMO, but given your latest code I would maybe adding a method to EventContext or whatever sinatra uses, called format, just to clean up things a bit like below
1 2 3 4 5 6 7 8 9 10 11
def format params[:format].to_sym || :html end get '/:id.?:format?' do @vent = Vent.get params[:id] case format when :xml : builder :show when :html : erb :show, :layout => false end end
mischamolhoek.myopenid.com
December 17, 2008, December 17, 2008 09:23, permalink
i would not use a case statement here, IMO its to much for two options
1 2 3 4 5
get '/:id.?:format?' do @vent = Vent.get(params[:id]) builder :show if params[:format] == xml erb :show, :layout => false if params[:format] == html end
Tj Holowaychuk
December 17, 2008, December 17, 2008 16:18, permalink
I would normally say that as well.. but then theres always the fact that you MAY be adding others, at which time you would have to refactor that whole chunk otherwise its really messy, plus the case looks a little cleaner. But Ideally I guess it would just be a respond_to type method
Nate
July 31, 2009, July 31, 2009 15:50, permalink
There is an awesome sinatra-respond_to plugin that does this for you:
1 2
sudo gem install cehoffman-sinatra-respond_to --source=http://gems.github.com
Chris Hoffman
February 1, 2010, February 01, 2010 22:38, permalink
With the deprecation of github gems I've rereleased sinatra-respond_to as a plugin on gemcutter. I've also updated it to support the 1.0 release of sinatra.
1
gem install sinatra-respond_to --source=http://gemcutter.org
Currently using sinatra framework to build a small app. I have these 2 methods to show info in different formats. Is there a way to get it in one method?