开发者

sinatra rest-client etag

开发者 https://www.devze.com 2023-02-06 11:45 出处:网络
My goal is to address \"lost update problem\" (see http://www.w3.org/1999/04/Editing/) in PUT operations.

My goal is to address "lost update problem" (see http://www.w3.org/1999/04/Editing/) in PUT operations. I am using sinatra, and as a client I use rest_client. How I can check if it works? My client always return 200 code. Am I using arguments of calling it correctly? (PUT itself works)

sinatra code:

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

client invocation:

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, res开发者_开发百科ult, &block|
    p response.code.to_s + " " + response
}

I tried already to put :if_none_match => "something", I tried :if_match. Nothing changes. How I can put headers into RestClient request? How to obtain sth different than 200 status? (ie 304 not modified)?


Your payload and headers are in the same hash. You have to specify the headers for RestClient in second hash. Try:

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

I am not sure if RestClient translates the headers correctly. If the above doesn't work, try it with:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号