2012-07-16 22 views
0

方案
我有一个西纳特拉应用
我有一个基于一定的命名路径西纳特拉应用JSON和路线

# Get Articles for a certain time period 

get '/frontpage/:type' do 
    case params[:type] 

    when "today" 
     @news = Article.find(...) 
    when "yesterday" 
     @news = Article.find(...) 
    when "week-ago" 
     @news = Article.find(...) 
    when "month-ago" 
     @news = Article.find(...) 
     else 
     not_found 
    end 

    erb :frontpage 

end 

问题
上取物品的路线是否有可能保持这条路线"/frontpage/:type",并显示一个.json页面,如果有人要求"/frontpage/:today.json"而不是"/frontpage/:type"

是否更好地为JSON请求创建单独的路由?

回答

1

您将不得不创建一条新路线。

虽然,那么您可以您的代码这样的:

get '/frontpage/:type' do 
    @news = get_articles(params[:type]) 
    erb :frontpage 
end 

get '/frontpage/:type.json' do 
    get_articles(params[:type]).json 
end 

def get_articles(type) 
    case 
    when "today" 
    Article.find(...) 
    when "yesterday" 
    Article.find(...) 
    when "week-ago" 
    Article.find(...) 
    when "month-ago" 
    Article.find(...) 
    else 
    raise "Unsupported type #{type}. Supported types are: today, yesterday, week-ago and month-ago." 
    end 
end 
+0

这是一个很好的例子。我一直认为这将是一种方法。从来没有考虑过像这样分手。 – alenm 2012-07-16 20:13:33

1

这其实可以用一个单一的途径来完成:

require 'rubygems' 
require 'sinatra' 

get %r{/frontpage/([^\.]+)\.?(.+)?} do |type, ext| 
    'the type is: ' + type + ' and the extension is: ' + "#{ext}" 
end 

您可以使用分机VAR来回报您的JSON内容如果它是非空的,并且值为'json'。