collection_association.rb 2.2 KB
Newer Older
1 2
# This class is inherited by the has_many and has_many_and_belongs_to_many association classes 

3 4
require 'active_record/associations'

5 6
module ActiveRecord::Associations::Builder
  class CollectionAssociation < Association #:nodoc:
7

8 9
    CALLBACKS = [:before_add, :after_add, :before_remove, :after_remove]

10
    def valid_options
11
      super + [:table_name, :before_add,
J
Jon Leighton 已提交
12
               :after_add, :before_remove, :after_remove, :extend]
13
    end
14

J
Jon Leighton 已提交
15
    attr_reader :block_extension, :extension_module
16

17 18
    def initialize(*args, &extension)
      super(*args)
19 20 21 22 23 24 25 26 27 28 29 30 31 32
      @block_extension = extension
    end

    def build
      wrap_block_extension
      reflection = super
      CALLBACKS.each { |callback_name| define_callback(callback_name) }
      reflection
    end

    def writable?
      true
    end

J
Jon Leighton 已提交
33 34 35 36 37
    def wrap_block_extension
      if block_extension
        @extension_module = mod = Module.new(&block_extension)
        silence_warnings do
          model.parent.const_set(extension_module_name, mod)
38 39
        end

J
Jon Leighton 已提交
40 41 42 43 44 45 46
        prev_scope = @scope

        if prev_scope
          @scope = proc { |owner| instance_exec(owner, &prev_scope).extending(mod) }
        else
          @scope = proc { extending(mod) }
        end
47
      end
J
Jon Leighton 已提交
48
    end
49

J
Jon Leighton 已提交
50 51 52
    def extension_module_name
      @extension_module_name ||= "#{model.name.demodulize}#{name.to_s.camelize}AssociationExtension"
    end
53

J
Jon Leighton 已提交
54 55
    def define_callback(callback_name)
      full_callback_name = "#{callback_name}_for_#{name}"
56

J
Jon Leighton 已提交
57 58 59 60
      # TODO : why do i need method_defined? I think its because of the inheritance chain
      model.class_attribute full_callback_name.to_sym unless model.method_defined?(full_callback_name)
      model.send("#{full_callback_name}=", Array(options[callback_name.to_sym]))
    end
61

62 63
    # Defines the setter and getter methods for the collection_singular_ids.

64
    def define_readers(mixin)
J
Jon Leighton 已提交
65 66
      super

67 68 69 70 71
      mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
        def #{name.to_s.singularize}_ids
          association(:#{name}).ids_reader
        end
      CODE
J
Jon Leighton 已提交
72
    end
73

74
    def define_writers(mixin)
J
Jon Leighton 已提交
75
      super
76

77 78 79 80 81
      mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
        def #{name.to_s.singularize}_ids=(ids)
          association(:#{name}).ids_writer(ids)
        end
      CODE
J
Jon Leighton 已提交
82
    end
83 84
  end
end