0

シナリオ
私は Sinatra アプリ
を持っています 特定の名前付きパスに基づいて記事を取得するルートを持っています

# 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

質問たとえば、誰かが代わりに.json を要求した場合、
このルートを維持して .json ページを表示することは可能ですか?"/frontpage/:type""/frontpage/:today.json""/frontpage/:type"

また

JSON のリクエスト専用に別のルートを作成する方が良いですか?

4

3 に答える 3

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
于 2012-07-16T15:32:08.343 に答える
1

これは、実際には単一のルートで実行できます。

require 'rubygems'
require 'sinatra'

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

ext var を使用して、json コンテンツが nil でなく、値が 'json' の場合は、json コンテンツを返すことができます。

于 2012-07-19T04:11:59.823 に答える