sinatra rest-client etag

时间:2011-01-25 16:15:30

标签: sinatra etag rest-client

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

sinatra代码:

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)?

1 个答案:

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