Module: CouchRest::Model::Persistence::ClassMethods

Defined in:
lib/couchrest/model/persistence.rb

Instance Method Summary collapse

Instance Method Details

#build_from_database(doc = {}, options = {}, &block) ⇒ Object

Creates a new instance, bypassing attribute protection and uses the type field to determine which model to use to instanatiate the new object.

Returns

a document instance

125
126
127
128
129
# File 'lib/couchrest/model/persistence.rb', line 125

def build_from_database(doc = {}, options = {}, &block)
  src = doc[model_type_key]
  base = (src.blank? || src == model_type_value) ? self : src.constantize
  base.new(doc, options.merge(:write_all_attributes => true), &block)
end

#create(attributes = {}, &block) ⇒ Object

Defines an instance and save it directly to the database

Returns

returns the reloaded document

135
136
137
138
139
# File 'lib/couchrest/model/persistence.rb', line 135

def create(attributes = {}, &block)
  instance = new(attributes, &block)
  instance.create
  instance
end

#create!(attributes = {}, &block) ⇒ Object

Defines an instance and save it directly to the database

Returns

returns the reloaded document or raises an exception

145
146
147
148
149
# File 'lib/couchrest/model/persistence.rb', line 145

def create!(attributes = {}, &block)
  instance = new(attributes, &block)
  instance.create!
  instance
end

#fail_validate!(document) ⇒ Object

Raise an error if validation failed.


176
177
178
# File 'lib/couchrest/model/persistence.rb', line 176

def fail_validate!(document)
  raise Errors::Validations.new(document)
end

#model_type_valueObject

The value to use for this model's model_type_key. By default, this shouls always be the string representation of the class, but if you need anything special, overwrite this method.


171
172
173
# File 'lib/couchrest/model/persistence.rb', line 171

def model_type_value
  to_s
end

#unique_id(method = nil, &block) ⇒ Object

Name a method that will be called before the document is first saved, which returns a string to be used for the document's _id.

Because CouchDB enforces a constraint that each id must be unique, this can be used to enforce eg: uniq usernames. Note that this id must be globally unique across all document types which share a database, so if you'd like to scope uniqueness to this class, you should use the class name as part of the unique id.


159
160
161
162
163
164
165
166
# File 'lib/couchrest/model/persistence.rb', line 159

def unique_id(method = nil, &block)
  return if method.nil? && !block
  define_method :set_unique_id do
    uniqid = method.nil? ? block.call(self) : send(method)
    raise ArgumentError, "unique_id cannot be nil nor empty" if uniqid.blank?
    self['_id'] ||= uniqid
  end
end