Module: PopulateMe::DocumentMixins::Persistence

Included in:
PopulateMe::Document
Defined in:
lib/populate_me/document_mixins/persistence.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



58
59
60
# File 'lib/populate_me/document_mixins/persistence.rb', line 58

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#attachment(f) ⇒ Object



15
16
17
18
# File 'lib/populate_me/document_mixins/persistence.rb', line 15

def attachment f
  attacher = WebUtils.resolve_class_name self.class.fields[f][:class_name]
  attacher.new self, f
end

#delete(o = {}) ⇒ Object

Deletion



47
48
49
50
51
# File 'lib/populate_me/document_mixins/persistence.rb', line 47

def delete o={}
  exec_callback :before_delete
  perform_delete
  exec_callback :after_delete
end

#perform_createObject



36
37
38
39
# File 'lib/populate_me/document_mixins/persistence.rb', line 36

def perform_create
  self.class.documents << self.to_h
  self.id
end

#perform_deleteObject



52
53
54
55
56
# File 'lib/populate_me/document_mixins/persistence.rb', line 52

def perform_delete
  index = self.class.documents.index{|d| d['id']==self.id }
  raise MissingDocumentError, "No document can be found with this ID: #{self.id}" if self.id.nil?||index.nil?
  self.class.documents.delete_at(index)
end

#perform_updateObject



40
41
42
43
44
# File 'lib/populate_me/document_mixins/persistence.rb', line 40

def perform_update
  index = self.class.documents.index{|d| d['id']==self.id }
  raise MissingDocumentError, "No document can be found with this ID: #{self.id}" if self.id.nil?||index.nil?
  self.class.documents[index] = self.to_h
end

#persistent_instance_variablesObject



5
6
7
8
9
10
11
12
13
# File 'lib/populate_me/document_mixins/persistence.rb', line 5

def persistent_instance_variables
  instance_variables.select do |k|
    if self.class.fields.empty?
      k !~ /^@_/
    else
      self.class.fields.key? k[1..-1].to_sym
    end
  end
end

#saveObject

Saving



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/populate_me/document_mixins/persistence.rb', line 21

def save
  return unless valid?
  exec_callback :before_save
  if new?
    exec_callback :before_create
    id = perform_create
    exec_callback :after_create
  else
    exec_callback :before_update
    id = perform_update
    exec_callback :after_update
  end
  exec_callback :after_save
  id
end