Skip to content

Instantly share code, notes, and snippets.

@Stanley
Created April 26, 2010 19:38
Show Gist options
  • Save Stanley/379777 to your computer and use it in GitHub Desktop.
Save Stanley/379777 to your computer and use it in GitHub Desktop.
Sample ruby CouchDB libraries
# CRUD
CouchFoo::Base.set_database(:host => "http://localhost:5984", :database => "krug")
class Address < CouchFoo::Base
property :number, Integer
property :street, String
property :postcode
end
Address.create(:number => 3, :street => "My Street", :postcode => "secret")
#=> #<Address number: 3, street: "My Street", postcode: "\"secret\"",
# _id: "bfe83d00-3400-012d-aac3-003048b9798a", _rev: "1-55491479b64cb96a5d2e506d84ed0bc3", ruby_class: "Address">
Address.find_by_street("My Street")
# Widoki
class Document < CouchFoo::Base
property :number, Integer
property :street, String
view :number_ordered, "function(doc) {emit([doc.number , doc.street], doc); }", nil, :descending => true
end
Document.number_ordered
# Realcje
class House < CouchFoo::Base
has_many :windows
end
class Window < CouchFoo::Base
property :house_id, String
belongs_to :house
end
# CRUD
CouchPotato::Config.database_name = "http://localhost:5984/krug"
class User
include CouchPotato::Persistence
property :name
end
user = User.new :name => 'joe'
# => #<User _id: '', _rev: '', created_at: '', updated_at: '', name: 'joe'>
CouchPotato.database.save_document user
CouchPotato.database.load_document("<id>").class #=> CouchRest::Document
# Widoki
class User
include CouchPotato::Persistence
property :name
view :all, :key => [:created_at, :name], :conditions => 'doc.completed === true'
end
CouchPotato.database.view User.all(:key => (Time.now- 10)..(Time.now), :descending => true)
# CRUD
class Line < CouchRestRails::Document
use_database :krug
property :no
property :timetables, :cast_as => ['Timetable']
timestamps!
end
line = Line.new #=> {"couchrest-type"=>"Line"}
line.no #=> nil
line['foo'] = "bar"
line.save #=> true
line #=> => {"couchrest-type"=>"Line", "updated_at"=>2010-04-26 19:47:22 +0200,
# "created_at"=>2010-04-26 19:47:22 +0200, "foo"=>"bar", "_id"=>"9e2cf863b2c23a8e7f8b8872b31e2606",
# "_rev"=>"1-72e75f5c3a551f5f15495d4e479b8752"}
Line.first
Line.get "9e2cf863b2c23a8e7f8b8872b31e2606"
Line.all
# Widoki
class Line < CouchRestRails::Document
use_database :krug
view_by :no,
:map =>
"function(doc){
if (doc['couchrest-type'] == 'Line'){
emit(doc.no, 1)
}
}"
end
Line.by_no :limit => 10
# Relacje
class Timetable < Hash
include CouchRest::CastedModel
attr_accessor :casted_by
alias_method :line, :casted_by
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment