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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章