Main image
23rd May
2009
written by cashplk

以下是一个简单的使用Ruby操作CouchDB数据库的代码:

新建fromRuby2CouchDB.rb文件,具体内容如下:

require 'net/http'
 
module Couch
  class Server
    def initialize(host, port, option = nil)
      @host = host;
      @port = port;
      @option = option;
    end
 
    def delete(uri)
      request(Net::HTTP::Delete.new(uri))
    end
 
    def get(uri)
      request(Net::HTTP::Get.new(uri))
    end
 
    # put json to request
    def put(uri, json)
      req = Net::HTTP::Put.new(uri)
      req["content.type"] = "application/json"
      req.body = json
      request(req)
    end
 
    def post(uri, json)
      req = Net::HTTP::Post.new(uri)
      req["content-type"] = "application/json"
      req.body = json
      request(req)
    end
 
    def request(req)
      res = Net::HTTP.start(@host, @port) {
        |http|http.request(req)
      }
      if (not 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}\nMETHOD:" +
 
          "#{req.method}\nURI:#{req.path}\n#{res.body}")
      raise e
    end
  end
 
end

在文件路径下,以命令行模式运行:irb,启动ruby编译器:
irb(main):001:0> require “fromRuby2CouchDB.rb”
=> true
irb(main):002:0> server = Couch::Server.new(“127.0.0.1″,”5984″)
=> #<Couch::Server:0xb7bdd258 @option=nil, @port=”5984″, @host=”127.0.0.1″>
irb(main):003:0> server.get(“/blog/”)
会插入一个新的数据库,名为blog。如果不对,会打印出相应的错误。成功后,可以在页面查看是否存在该数据库。

Tags: , , ,

Leave a Reply

Powered by WP Hashcash

Spam Protection by WP-SpamFree