Module: Hanswurst::Callbacks

Included in:
Hanswurst
Defined in:
lib/hanswurst/callbacks.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/hanswurst/callbacks.rb', line 3

def self.included(base)
  base.class_eval do
    # mimic the create_document method from https://github.com/langalex/couch_potato/blob/master/lib/couch_potato/database.rb  
    before_create do
      ok = true
      self.hanswurst_data.each do |role,document|
        if document.is_a?(CouchPotato::Persistence)
          document.errors.clear
          document.created_at ||= (Time.zone || Time).now
          document.updated_at = (Time.zone || Time).now
          (ok = false) if false == document.run_callbacks(:validation_on_save) do
            (ok = false) if false == document.run_callbacks(:validation_on_create) do
              raise(CouchPotato::Database::ValidationsFailedError.new(["role: " + role].concat(document.errors.full_messages))) unless database.send(:valid_document?, document)
            end
          end

          (ok = false) if false == document.run_callbacks(:save) do
            (ok = false) if false == document.run_callbacks(:create) do
              true
            end
          end
        end
      end
      ok
    end

    # mimic the update_document method from https://github.com/langalex/couch_potato/blob/master/lib/couch_potato/database.rb  
    before_update do
      ok = true
      self.hanswurst_data.each do |role,document|
        if document.is_a?(CouchPotato::Persistence)
          document.errors.clear
          document.created_at ||= (Time.zone || Time).now
          document.updated_at = (Time.zone || Time).now
          (ok = false) if false == document.run_callbacks(:validation_on_save) do
            (ok = false) if false == document.run_callbacks(:validation_on_update) do
              raise(CouchPotato::Database::ValidationsFailedError.new(["role: " + role].concat(document.errors.full_messages))) unless database.send(:valid_document?, document)
            end
          end

          (ok = false) if false == document.run_callbacks(:save) do
            (ok = false) if false == document.run_callbacks(:update) do
              true
            end
          end
        end      
      end
      ok
    end

    # mimic the destroy_document method from https://github.com/langalex/couch_potato/blob/master/lib/couch_potato/database.rb  
    before_destroy do
      ok = true
      self.hanswurst_data.each do |role,document|
        if document.is_a?(CouchPotato::Persistence)
          (ok = false) if false == document.run_callbacks(:destroy) do
            true
          end
        end
      end
      ok
    end
  end
end