Module: HasModerated::ModeratedAttributes::ClassMethods

Defined in:
lib/has_moderated/moderated_attributes.rb

Instance Method Summary collapse

Instance Method Details

#has_moderated(*args, &block) ⇒ Object



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
# File 'lib/has_moderated/moderated_attributes.rb', line 4

def has_moderated *args, &block
  HasModerated::Common::init(self)
  # Lazily include the instance methods so we don't clutter up
  # any more ActiveRecord models than we have to.
  send :include, InstanceMethods

  cattr_accessor :moderated_attributes
  cattr_accessor :moderated_options

  self.moderated_attributes ||= []
  self.moderated_options ||= {}

  args.each do |arg|
    if arg.class == Hash || arg.class == HashWithIndifferentAccess
      self.moderated_options = self.moderated_options.merge(arg)
    else
      self.moderated_attributes.push(arg.to_s)
    end
  end

  # send moderated attributes to moderation before saving the model
  before_save do
    if self.valid? && !self.moderation_disabled &&
      # don't save moderated attributes if create is moderated and it's a new record
      !(self.class.respond_to?("moderated_create_options") && new_record?)
      moderations = self.to_moderation
      if self.id.blank?
        @pending_moderations ||= []
        @pending_moderations.concat(moderations)
      end
    end
  end

  # when creating a new record, we must update moderations' id after it is known (after create)
  # TODO is this even necessary when using assoc.create ?
  after_create do
    if !self.id.blank? && !@pending_moderations.blank?
      @pending_moderations.each do |m|
        m.moderatable_id = self.id
        m.save
      end
      @pending_moderations.clear
    end
  end
end