[Ruby] Ruby: Update CouchDB data (Update)

less than 1 minute read

couch_update.rb


#! /usr/bin/ruby
# -*- encoding: utf-8 -*-
#
# couch_update.rb
#
#     Jul/31/2020
#
# ---------------------------------------------------------------------
require 'faraday'
require 'json'
require 'date'
#
# ---------------------------------------------------------------------
STDERR.puts "*** 開始 ***"
#
key_in = ARGV[0]
population_in = ARGV[1].to_i
puts key_in,population_in

URL="http://localhost:5984/nagano/" + key_in
#
res = Faraday.get URL

puts res.status

if res.status == 200 then
 json_str = res.body

 data_aa=JSON.parse(json_str)
#
 puts data_aa
 puts data_aa["_rev"]
 puts data_aa["name"]
#
 args = {}
 args["name"] = data_aa["name"]
 args["population"] = population_in
 args["date_mod"] = Date.today

 url_up = URL + "?rev=" + data_aa["_rev"]

 con = Faraday.new 
 res = con.put do |req|
  req.url url_up
  req.headers['Content-Type'] = 'application/json'
  req.body = JSON.pretty_generate(args)
 end

 puts res.status
end

STDERR.puts "*** 終了 ***"
# ---------------------------------------------------------------------

実行

./couch_update.rb t2029 4213500