Ruby&CouchDB之Hello World

require 'net/http'

module Couch
class Server
#类默认构造函数名,ruby中null使用nil表示
def initialize(host,port,options = nil)
#‘@’表示类成员变量
@host=host
@port=port
@options=options
end

def put(uri,json)
#'::'表示常量的引用
req = Net::HTTP::Put.new(uri)
req["content-type"] = "application/json"
req.body = json
request(req)
end

def get(uri)
request(Net::HTTP::Get.new(uri))
end

def delete(uri)
request(Net::HTTP::Delete.new(uri))
end

def request(req)
res = Net::HTTP.start(@host,@port){|http| http.request(req)}
#判断方法一般以‘?’结尾
unless res.kind_of?(Net::HTTPSuccess){
handle_error(req,res)
}
end
res
end

private
def handle_error(req,res)
e = RuntimeError.new("#{res.code}:#{res.message}\n METHOD:#{req.method}\nURI:#{req.uri}\n#{req.body}")
raise e
end
end
end


Test Class
#引用自己写的Module时,注意路径问题
require 'couchdb/Couch'

server = Couch::Server.new("localhost","5984")
server.put("/foo","hello world")
#Json字符串的构造方式
doc = <<-JSON
{"name":"xianning","sex":"male"}
JSON
puts doc
server.put("/foo/doc_id",doc)
res = server.get("/foo/doc_id")
puts res.body
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值