Last active
August 29, 2015 14:03
-
-
Save weapp/d59f42e33aca77ed71d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rest_client' | |
require 'json' | |
require 'pp' | |
COUCHDB = "http://localhost:5984/dbname" | |
filters_doc = { | |
"_id" => "_design/app", | |
"filters" => { | |
"people"=> "function(doc, req) { return doc.type == 'person' }" | |
} | |
} | |
class JsonApiClient < RestClient::Resource | |
DEFAULT_OPTIONS = {:content_type => :json, :accept => :json} | |
def get_with_json(*args, &block) | |
r = get_without_json(*args,&block) | |
JSON.parse(r) | |
end | |
alias_method :get_without_json, :get | |
alias_method :get, :get_with_json | |
def post_with_json(content, options={}, &block) | |
options = options.merge(DEFAULT_OPTIONS) | |
content = parse_content(content) | |
r = post_without_json(content, options, &block) | |
JSON.parse(r) | |
end | |
alias_method :post_without_json, :post | |
alias_method :post, :post_with_json | |
def put_with_json(content, options={}, &block) | |
options = options.merge(DEFAULT_OPTIONS) | |
content = parse_content(content) | |
r = put_without_json(content, options, &block) | |
JSON.parse(r) | |
end | |
alias_method :put_without_json, :put | |
alias_method :put, :put_with_json | |
def delete_with_json(*args, &block) | |
r = delete_without_json(*args,&block) | |
JSON.parse(r) | |
end | |
alias_method :delete_without_json, :delete | |
alias_method :delete, :delete_with_json | |
private | |
def parse_content(content) | |
content = content.to_json if content.is_a? Hash | |
content | |
end | |
end | |
class CouchClient < JsonApiClient | |
def create_or_update(doc) | |
id = doc["_id"] || doc[:_id] | |
rev = self[id].get["_rev"] | |
doc["_rev"] = rev | |
# update | |
self[id].put(doc) | |
rescue RestClient::ResourceNotFound | |
# create | |
self.post(doc) | |
end | |
def changes(params={}, &block) | |
loop do | |
res = self["_changes"].get(params: params) | |
params[:since] = res["last_seq"] | |
res["results"].each(&block) | |
break if res["results"].empty? | |
end | |
params[:since] || 0 | |
end | |
end | |
couch = CouchClient.new(COUCHDB) | |
couch.create_or_update(filters_doc) | |
since = couch[".since"].get{|r| r }["since"] || 0 | |
since = couch.changes(since: since, limit: 50, filter:"app/people", include_docs: "true") do |hash| | |
if hash["deleted"] | |
puts "deleted: #{hash['id']}" | |
else | |
puts "updated: #{hash['id']}" | |
pp hash["doc"] | |
end | |
end | |
puts since | |
couch.create_or_update(_id: ".since", type: "metadata", since: since) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment