Module: HasModerated::Associations::Base::ClassMethods

Defined in:
lib/has_moderated/associations/base.rb

Overview

Class methods included into ActiveRecord::Base so that they can be called in ActiveRecord models.

Instance Method Summary collapse

Instance Method Details

#has_moderated_association(*args) ⇒ Object

Will moderate the passed in associations if they are supported. Example: has_moderated_association(:posts, :comments). Also supports passing :all to moderate all associations, but I personally do not recommend using this option.

Parameters:

  • associations (Hash)

    the associations to moderate



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
# File 'lib/has_moderated/associations/base.rb', line 14

def has_moderated_association(*args)
  # some common initialization (lazy loading)
  HasModerated::Common::init(self)

  args = [args] unless args.kind_of? Array

  # handle :all option
  assoc_names = if args.include?(:all)
    self.reflections.keys.reject do |r|
      r == :moderations
    end
  else
    args
  end

  # process associations + lazy loading
  assoc_names.map{ |name| self.reflections[name] }.each do |assoc|
    case assoc.macro
      when :has_many then
        self.send :extend, HasModerated::Associations::Collection::ClassMethods
        has_moderated_collection_association(assoc)
      when :has_one then
        self.send :extend, HasModerated::Associations::HasOne::ClassMethods
        has_moderated_has_one_association(assoc)
      when :has_and_belongs_to_many then
        self.send :extend, HasModerated::Associations::Collection::ClassMethods
        has_moderated_collection_association(assoc)
      else raise "don't know how to moderate association macro #{assoc.macro}"
    end
  end
end