2011-01-25 79 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"'}