aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/associations/builder/association.rb
diff options
context:
space:
mode:
authorJon Leighton <j@jonathanleighton.com>2011-02-21 01:09:41 +0000
committerAaron Patterson <aaron.patterson@gmail.com>2011-02-21 10:16:15 -0800
commit52f8e4b9dae6137fcd95793dffc26ddff80b623e (patch)
tree11a80259a618472810155ca46fd826246aab9906 /activerecord/lib/active_record/associations/builder/association.rb
parenta5274bb52c058bae69476bee3c95f472513a5725 (diff)
downloadrails-52f8e4b9dae6137fcd95793dffc26ddff80b623e.tar.gz
rails-52f8e4b9dae6137fcd95793dffc26ddff80b623e.tar.bz2
rails-52f8e4b9dae6137fcd95793dffc26ddff80b623e.zip
Use proper objects to do the work to build the associations (adding methods, callbacks etc) rather than calling a whole bunch of methods with rather long names.
Diffstat (limited to 'activerecord/lib/active_record/associations/builder/association.rb')
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb53
1 files changed, 53 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
new file mode 100644
index 0000000000..96fca97440
--- /dev/null
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -0,0 +1,53 @@
+module ActiveRecord::Associations::Builder
+ class Association #:nodoc:
+ class_attribute :valid_options
+ self.valid_options = [:class_name, :foreign_key, :select, :conditions, :include, :extend, :readonly, :validate]
+
+ # Set by subclasses
+ class_attribute :macro
+
+ attr_reader :model, :name, :options, :reflection
+
+ def self.build(model, name, options)
+ new(model, name, options).build
+ end
+
+ def initialize(model, name, options)
+ @model, @name, @options = model, name, options
+ end
+
+ def build
+ validate_options
+ reflection = model.create_reflection(self.class.macro, name, options, model)
+ define_accessors
+ reflection
+ end
+
+ private
+
+ def validate_options
+ options.assert_valid_keys(self.class.valid_options)
+ end
+
+ def define_accessors
+ define_readers
+ define_writers
+ end
+
+ def define_readers
+ name = self.name
+
+ model.redefine_method(name) do |*params|
+ association(name).reader(*params)
+ end
+ end
+
+ def define_writers
+ name = self.name
+
+ model.redefine_method("#{name}=") do |value|
+ association(name).writer(value)
+ end
+ end
+ end
+end