Created
December 8, 2009 09:01
-
-
Save karmi/251533 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
# Minimal "ActiveModel-like" wrapper for CouchDB to replace ActiveRcord-based model | |
require 'rubygems' | |
require 'json' | |
require 'httparty' | |
require 'ostruct' | |
class Time | |
def to_json(options={}); self.strftime('"%Y/%m/%d %H:%M:%S +0000"'); end | |
end | |
class Array | |
alias_method :count, :size | |
end | |
module CouchDB | |
class Document < OpenStruct | |
def self.database_name=(name); @database_name = name; end | |
def self.database_name; @database_name; end | |
include HTTParty | |
format :json | |
def initialize(params={}) | |
super | |
self.id ||= self.title.to_s.gsub(/\s/, '-').downcase | |
self.created_at = Time.now | |
self.type = self.class.to_s.downcase | |
self | |
end | |
def self.find_all | |
response = get("/_design/#{self.to_s.downcase}/_view/by_name") | |
response['rows'].map { |p| new(p['value']) } | |
end | |
class << self | |
alias_method :all, :find_all | |
end | |
def self.find(id) | |
new get('/'+id) | |
end | |
def update_attributes(params={}) | |
params.each_pair do |key, value| | |
self.send(:"#{key}=", value) if self.respond_to?(key.to_sym) | |
end | |
self.save | |
end | |
def save | |
response = self.class.put('/'+self.id, :body => self.to_json) | |
if response.code.to_s == '201' | |
self._rev = JSON.parse(response.body)['rev'] | |
self | |
else | |
raise Exception, response.body | |
end | |
end | |
def destroy | |
puts self.inspect | |
response = self.class.delete('/'+self.id+'?rev='+self._rev) | |
if response.code.to_s == '200' | |
JSON.parse(response.body)['rev'] | |
else | |
raise Exception, response.body | |
end | |
end | |
def to_json | |
@table.to_json | |
end | |
def to_param | |
self.id.to_s || nil | |
end | |
def errors | |
[] | |
end | |
def new_record? | |
self.id ? true : false | |
end | |
def id; @table[:id]; end | |
def type; @table[:type]; end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment