association.rb 2.1 KB
Newer Older
1 2
module ActiveRecord::Associations::Builder
  class Association #:nodoc:
3 4 5
    class << self
      attr_accessor :valid_options
    end
6

7
    self.valid_options = [:class_name, :foreign_key, :validate]
8

9
    attr_reader :model, :name, :scope, :options, :reflection
10

11 12
    def self.build(*args, &block)
      new(*args, &block).build
13 14
    end

15 16 17 18
    def initialize(model, name, scope, options)
      @model   = model
      @name    = name

J
Jon Leighton 已提交
19
      if scope.is_a?(Hash)
20 21
        @scope   = nil
        @options = scope
J
Jon Leighton 已提交
22 23 24
      else
        @scope   = scope
        @options = options
25
      end
J
Jon Leighton 已提交
26 27 28 29 30

      if @scope && @scope.arity == 0
        prev_scope = @scope
        @scope = proc { instance_exec(&prev_scope) }
      end
31 32 33 34
    end

    def mixin
      @model.generated_feature_methods
35 36
    end

37 38
    include Module.new { def build; end }

39 40 41
    def build
      validate_options
      define_accessors
42 43 44 45 46 47 48 49 50 51 52
      @reflection = model.create_reflection(macro, name, scope, options, model)
      super # provides an extension point
      @reflection
    end

    def macro
      raise NotImplementedError
    end

    def valid_options
      Association.valid_options
53 54
    end

J
Jon Leighton 已提交
55 56 57
    def validate_options
      options.assert_valid_keys(valid_options)
    end
58

J
Jon Leighton 已提交
59 60 61 62
    def define_accessors
      define_readers
      define_writers
    end
63

J
Jon Leighton 已提交
64 65 66 67
    def define_readers
      name = self.name
      mixin.redefine_method(name) do |*params|
        association(name).reader(*params)
68
      end
J
Jon Leighton 已提交
69
    end
70

J
Jon Leighton 已提交
71 72 73 74
    def define_writers
      name = self.name
      mixin.redefine_method("#{name}=") do |value|
        association(name).writer(value)
75
      end
J
Jon Leighton 已提交
76
    end
77

J
Jon Leighton 已提交
78 79 80
    def validate_dependent_option(valid_options)
      unless valid_options.include? options[:dependent]
        raise ArgumentError, "The :dependent option must be one of #{valid_options}, but is :#{options[:dependent]}"
81
      end
82

J
Jon Leighton 已提交
83 84 85 86 87
      if options[:dependent] == :restrict
        ActiveSupport::Deprecation.warn(
          "The :restrict option is deprecated. Please use :restrict_with_exception instead, which " \
          "provides the same functionality."
        )
88
      end
J
Jon Leighton 已提交
89
    end
90
  end
91
end