Module: ChillDB

Defined in:
lib/chill.rb

Overview

The main ChillDB module - This is where it all starts

Throughout these docs you’ll find classes under ChillDB. In a real application you’ll call ChillDB.goes :SomethingOrOther and from then on, substitute ChillDB for SomethingOrOther when refering to class names. ChillDB effectively creates a copy of itself linked to a database called SomethingOrOther on the local couchdb server. Check out ChillDB.goes for more details on getting started. Throughout the documentation, you’ll see KittensApp as a placeholder - imagine ChillDB.goes :KittensApp has been run beforehand.

Defined Under Namespace

Classes: BulkUpdateErrors, Database, Design, Document, IndifferentHash, List

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.goes(database_name, options = {}) ⇒ Object

Creates a copy of ChillDB linked to a database named with the first argument. You can also provide host, port, user, and pass options as a hash to connect chill to a remote couchdb server or just provide authentication info. Once ChillDB.goes has been called, you’ll use the database_name instead of ChillDB when refering to chill’s classes throughout your app.

Example:

ChillDB.goes :KittensApp

# load 'frederick' from the KittensApp database
# on the locally installed couch server
KittensApp['frederick'] #=> <ChillDB::Document>

Options:

user: 'couchdb_user'
pass: 'couchdb_password'
host: 'my-couch-server.com'
port: 5984
path: '/my-database/'

Default options: ChillDB connects to localhost:5984/db-name-hyphenated/. When couch is freshly installed on a server, defaults will will work without any extra setup. You might want to add authentication if your server has multiple users, or you maybe allowing remote web access to couchdb.



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/chill.rb', line 46

def self.goes database_name, options = {}
  submod = Module.new do
    extend ChillDB
    @@database = ChillDB::Database.new database_name, options
    @@templates = {}
  end
  self.constants(false).each do |const|
    submod.const_set(const, self.const_get(const));
  end
  Object.const_set(database_name, submod)
end

Instance Method Details

#[]=(document, hash) ⇒ Object

Commit a ChillDB::Document or a Hash to the database with a specific _id. This method is useful for quickly storing bits of information. For more involved applications, using ChillDB::Document objects directly is best.

Returns a copy of the data as a ChillDB::Document, with _rev set to it’s new value on the server.

Example:

KittensApp['bigglesworth'] = {kind: 'cat', softness: 11}


145
146
147
148
149
150
151
# File 'lib/chill.rb', line 145

def []= document, hash
  raise "Not a hash?" unless hash.is_a? Hash
  hash = hash.dup
  hash['_id'] = document
  return hash.commit! if hash.is_a? ChillDB::Document
  return ChillDB::Document.new(@@database, hash).commit!
end

#commit!(*documents) ⇒ Object

Commit an array of ChillDB::Documents and/or Hashes to the server as new or updated documents. This collection can include ChillDB::Document’s marked for deletion, and is the best way to update several documents at the same time. All documents which can be committed will be, and any which cause errors will be reported via a raised ChillDB::BulkUpdateErrors.



158
159
160
# File 'lib/chill.rb', line 158

def commit! *documents
  list(documents.map { |arg| arg.respond_to?(:docs)? arg.docs : arg }.flatten(1)).commit!
end

#databaseObject

Returns this app’s ChillDB::Database instance



198
199
200
# File 'lib/chill.rb', line 198

def database
  @@database
end

#delete!(*documents) ⇒ Object

A shortcut for #commit! which marks the documents for deletion before applying the commit, effectively bulk deleting them. If any deletions fail a ChillDB::BulkUpdateErrors will be raised with info. All deletions which can succeed, will.



166
167
168
# File 'lib/chill.rb', line 166

def delete! *documents
  list(documents.map { |arg| arg.respond_to?(:docs)? arg.docs : arg }.flatten(1)).delete!
end

#design(name) ⇒ Object

Loads or creates a new ChillDB::Design with a specified name. Designs are used to create views, which create cached high speed document indexes for searching, sorting, and calculating.



98
99
100
# File 'lib/chill.rb', line 98

def design name
  ChillDB::Design.new @@database, name
end

#document(id = false) ⇒ Object Also known as: []

Loads or creates a document with a specified _id. If no _id is specified a new blank document is created which will be assigned a fresh UUID when unless you specify one before committing it. You can optionally provide values for a new document as a hash argument. Note that documents created in this way are not saved to the database unless you use ChillDB::Document#commit! or pass them to #commit!

Example:

KittensApp['fredrick']
  #=> {"_id"=>"cheezly", "color"=>"invisible", "dislikes"=>["silly business"], ... }
KittensApp[['fredrick', 'cheezly']] 
  #=> [{"_id"=>"fredrick", ... }, {"_id"=>"cheezly", ... }]
KittensApp[]
  #=> {}
KittensApp[billy: 'cool', margret: 'not cool']
  #=> {"billy"=>"cool", "margret"=>"not cool", "_id"=>"df2c3d11-d50a-4db9-8f57-04fd4d511ded"}

Returns a ChillDB::Document



120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/chill.rb', line 120

def document id = false
  if id.respond_to? :to_ary
    list = id.to_ary.map { |i| i.to_s }
    response = @@database.http('_all_docs?include_docs=true').post({ keys: list }.to_json)
    ChillDB::List.load(JSON.parse(response), database: @@database)
  elsif id.respond_to? :to_str
    ChillDB::Document.load(@@database, id.to_str)
  elsif id.respond_to? :to_hash
    ChillDB::Document.new(@@database).reset(id)
  else # just make a new blank document
    ChillDB::Document.new(@@database)
  end
end

#everythingObject

Queries the server for every document. Returns a ChillDB::List.

This method is mainly useful for maintenence and mockups. Using #everything in production apps is strongly discouraged, as it has severe scalability implications - use a ChillDB::Design view instead if you can.

Example:

# The worst way to look up a document. Never ever do this.
all_of_them = KittensApp.everything # download all documents from server
fredrick = all_of_them['fredrick'] # locally find just the one you want
# Now ruby's garbage collector can happily remove every document you
# ever made from memory. Yay!


191
192
193
194
195
# File 'lib/chill.rb', line 191

def everything
  list = ChillDB::List.load(JSON.parse(@@database.http('_all_docs?include_docs=true').get.body))
  list.database = @@database
  return list
end

#list(array = []) ⇒ Object

creates a new ChillDB::List from an array of ChillDB::Documents and hashes. This method is mainly used internally for #commit! and #delete! You shouldn’t need to use this method.



173
174
175
176
177
# File 'lib/chill.rb', line 173

def list array = []
  list = ChillDB::List.from_array array
  list.database = @@database
  return list
end

#open(*args) ⇒ Object

Gets a reference to a resource on the database server, useful mainly internally. You shouldn’t need to use this method unless using Couch features chill doesn’t yet have an interface for.



205
206
207
208
209
# File 'lib/chill.rb', line 205

def open *args
  headers = { accept: '*/*' }
  headers.merge! args.pop if args.last.respond_to? :to_hash
  @@database.http(args.map { |item| URI.escape(item, /[^a-z0-9_.-]/i) }.join('/'), headers)
end

#template(kind) ⇒ Object

Gets a copy of a template previously defined using #templates. further info on usage is in the description of #templates.



89
90
91
92
93
# File 'lib/chill.rb', line 89

def template kind
  properties = @@templates[kind.to_sym].dup
  properties[:kind] = kind.to_s
  ChillDB::Document.new(@@database, properties)
end

#templates(obj) ⇒ Object

#templates stores a collection of new document templates. This is a handy shortcut to hold your different types of documents. Templates automatically have a property called ‘kind’ which is assigned to the template’s name, which can be handy when writing views. They also provide a great place to write in default values, and are just generally handy as a place to keep a little note to yourself what fields you might expect in a type of document.

Example:

KittensApp.templates(
  cat: {
    color: 'unknown',
    softness: 5,
    likes: ['exploding', 'cupcakes'],
    dislikes: ['dark matter']
  }
)

# use the template, extend it with specific info, and save it!
new_cat = KittensApp.template(:cat).merge(
  color: 'octarine',
  softness: 13,
  _id: 'bjorn'
).commit!


82
83
84
85
# File 'lib/chill.rb', line 82

def templates obj
  @@templates.merge!(obj) if obj and obj.is_a? Hash
  return @@templates
end