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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
|
# File 'lib/conscript/orm/activerecord.rb', line 8
def register_for_draft(options = {})
cattr_accessor :conscript_options, :instance_accessor => false do
{
associations: [],
ignore_attributes: [self.primary_key, 'type', 'created_at', 'updated_at', 'draft_parent_id', 'is_draft']
}
end
self.conscript_options.each_pair {|key, value| self.conscript_options[key] = Array(value) | Array(options[key]) }
self.conscript_options[:associations].map!(&:to_sym)
self.conscript_options[:ignore_attributes].map!(&:to_s)
default_scope { where(is_draft: false) }
belongs_to :draft_parent, class_name: self
has_many :drafts, conditions: {is_draft: true}, class_name: self, foreign_key: :draft_parent_id, dependent: :destroy, inverse_of: :draft_parent
before_save :check_no_drafts_exist
if self.respond_to? :uploaders
self.uploaders.keys.each {|attribute| skip_callback :commit, :after, :"remove_#{attribute}!" }
after_commit :clean_uploaded_files_for_draft!, :on => :destroy
end
class_eval " def self.drafts\n where(is_draft: true)\n end\n\n def save_as_draft!\n raise Conscript::Exception::AlreadyDraft if is_draft?\n draft = new_record? ? self : dup(include: self.class.conscript_options[:associations])\n draft.is_draft = true\n draft.draft_parent = self unless new_record?\n self.class.base_class.unscoped { draft.save! }\n draft\n end\n\n def publish_draft\n raise Conscript::Exception::NotADraft unless is_draft?\n return self.update_attribute(:is_draft, false) if !draft_parent_id\n ::ActiveRecord::Base.transaction do\n draft_parent.assign_attributes attributes_to_publish, without_protection: true\n\n self.class.conscript_options[:associations].each do |association|\n case reflections[association].macro\n when :has_many\n draft_parent.send(association.to_s + \"=\", self.send(association).collect {|child| child.dup })\n end\n end\n\n draft_parent.drafts.destroy_all\n draft_parent.save!\n end\n draft_parent\n end\n\n def uploader_store_param\n draft_parent_id.nil? ? to_param : draft_parent.to_param\n end\n\n private\n def check_no_drafts_exist\n drafts.count == 0\n end\n\n def attributes_to_publish\n attributes.reject {|attribute| self.class.conscript_options[:ignore_attributes].include?(attribute) }\n end\n\n # Clean up CarrierWave uploads if there are no other instances using the files.\n #\n def clean_uploaded_files_for_draft!\n self.class.uploaders.keys.each do |attribute|\n filename = attributes[attribute.to_s]\n self.send(\"remove_\" + attribute.to_s + \"!\") if !draft_parent_id or draft_parent.drafts.where(attribute => filename).count == 0\n end\n end\n RUBY\nend\n"
|