2011-01-25 67 views
1

我的目标是解决PUT操作中的“丢失更新问题”(请参阅​​http://www.w3.org/1999/04/Editing/)。 我正在使用sinatra,并且作为客户端使用rest_client。我如何检查它是否有效?我的客户总是返回200个代码。我是否使用正确调用它的参数? (把自己的作品)sinatra rest-client etag

西纳特拉代码:

put '/players/:id' do |id| 
    etag 'something' 
    if Player[id].nil? then 
     halt 404 
    end 
    begin 
     data = JSON.parse(params[:data]) 
     pl = Player[id] 
     pl.name = data['name'] 
     pl.position = data['position'] 
     if pl.save 
      "Resource modified." 
     else 
      status 412 
      redirect '/players' 
     end 

    rescue Sequel::DatabaseError 
     409 #Conflict - The request was unsuccessful due to a conflict in the state of the resource. 
    rescue Exception => e 
     400 
     puts e.message 
    end 
end 

客户端调用:

player = {"name" => "John Smith", "position" => "def"}.to_json 

RestClient.put('http://localhost:4567/players/1', {:data => player, :content_type => :json, :if_none_match => '"something"'}){ |response, request, result, &block| 
    p response.code.to_s + " " + response 
} 

我想已经把:if_none_match => “东西”,我想:if_match。没有什么变化。 如何将标题放入RestClient请求? 如何获得不同于200的身份? (即304未修改)?

回答

0

您的有效负载和标头位于相同的散列。您必须在第二个散列中指定RestClient的标头。请尝试:

player = {"name" => "John Smith", "position" => "def"}.to_json 
headers = {:content_type => :json, :if_none_match => '"something"'} 

RestClient.put('http://localhost:4567/players/1', {:data => player}, headers) do |response, request, result, &block| 
    p response.code.to_s + " " + response 
end 

我不确定RestClient是否正确翻译了标题。如果上述不起作用,请尝试使用:

headers = {'Content-Type' => :json, 'If-None-Match' => '"something"'}