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

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

Instance Method Summary collapse

Instance Method Details

#create(attributes = {}) ⇒ Object

Defines an instance and save it directly to the database

Returns

returns the reloaded document


108
109
110
111
112
# File 'lib/couchrest/model/persistence.rb', line 108

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

#create!(attributes = {}) ⇒ Object

Defines an instance and save it directly to the database

Returns

returns the reloaded document or raises an exception


118
119
120
121
122
# File 'lib/couchrest/model/persistence.rb', line 118

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

#create_from_database(doc = {}) ⇒ Object

Creates a new instance, bypassing attribute protection

Returns

a document instance


99
100
101
102
# File 'lib/couchrest/model/persistence.rb', line 99

def create_from_database(doc = {})
  base = (doc[model_type_key].blank? || doc[model_type_key] == self.to_s) ? self : doc[model_type_key].constantize
  base.new(doc, :directly_set_attributes => true)      
end

#fail_validate!(document) ⇒ Object

Raise an error if validation failed.



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

def fail_validate!(document)
  raise Errors::Validations.new(document)
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.



132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/couchrest/model/persistence.rb', line 132

def unique_id method = nil, &block
  if method
    define_method :set_unique_id do
      self['_id'] ||= self.send(method)
    end
  elsif block
    define_method :set_unique_id do
      uniqid = block.call(self)
      raise ArgumentError, "unique_id block must not return nil" if uniqid.nil?
      self['_id'] ||= uniqid
    end
  end
end