Sinatra App JSON和路由

时间:2012-07-16 02:56:12

标签: ruby json activerecord routes sinatra

方案
我有一个Sinatra App
我有一个基于某个命名路径获取文章的路由

# 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"而不是"/frontpage/:today.json",是否可以保留此路线"/frontpage/:type"并显示.json页面?

OR

创建一个专门针对JSON请求的单独路由是否更好?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

这实际上可以通过一条路线完成:

require 'rubygems'
require 'sinatra'

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

你可以使用ext var返回你的json内容,如果它是非nill的,并且值为'json'。

答案 2 :(得分:0)

route order很重要。

比较此应用程序,首先使用.json

require "sinatra"
require "sinatra/contrib/all"

get "/greet/:name.json" do |name|
  json ({"greeting" => greeting(name)})
end

get "/greet/:name" do |name|
  greeting name
end

def greeting(name)
  "Hello #{name}"
end

使用此应用,最后一个.json

require "sinatra"
require "sinatra/contrib/all"

get "/greet/:name" do |name|
  greeting name
end

get "/greet/:name.json" do |name|
  json ({"greeting" => greeting(name)})
end

def greeting(name)
  "Hello #{name}"
end

第一个:

$ curl localhost:4567/greet/frank
Hello frank

$ curl localhost:4567/greet/frank.json
{"greeting": "Hello frank"}

但是第二个,

$ curl localhost:4567/greet/frank
Hello frank

$ curl localhost:4567/greet/frank.json
Hello frank.json