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