Permalink
Browse files

Added inherited associations and validation. Thanks, Eric!

git-svn-id: svn+ssh://svn0.sea.apvio.net/home/rwl4/inherits_from@4 bd10a536-b517-0410-99c0-c9a68740b5c0
  • Loading branch information...
1 parent 519ba09 commit 71c50926db65307614fd86620641c25b38e69095 rwl4 committed Apr 20, 2007
Showing with 32 additions and 18 deletions.
  1. +2 −0 CREDITS
  2. +30 −18 lib/inherits_from.rb
View
2 CREDITS
@@ -0,0 +1,2 @@
+Special thanks to:
+Eric Gerlach (egerlach at feds.uwaterloo.ca) for his work on inheritance through associations and validation.
View
48 lib/inherits_from.rb
@@ -35,14 +35,43 @@ class ActiveRecord::Base
# end
def self.inherits_from(association_id, options = {})
belongs_to association_id
+ validates_associated association_id
reflection = create_reflection(:belongs_to, association_id, options, self)
association_class = Object.const_get(reflection.class_name)
inherited_column_names = association_class.column_names.reject { |c| self.column_names.grep(c).length > 0 || c == "type"}
+
+ inherited_reflections = association_class.reflections.map { |key,value| key.to_s }
+
+ (inherited_column_names + inherited_reflections).each do |name|
+ define_method(name) do
+ init_inherited_assoc(association_id)
+ klass = send(association_id)
+
+ klass.send(name)
+ end
+
+ define_method("#{name}=") do |new_value|
+ init_inherited_assoc(association_id)
+ klass = send(association_id)
+
+ klass.send("#{name}=", new_value)
+ end
+ end
- inherited_column_names.each { |name| alias_associated_attr(association_id, name) }
+ inherited_reflections.each do |name|
+ %w{ build create }.each do |method|
+ define_method("#{method}_#{name}") do |*params|
+ init_inherited_assoc(association_id)
+ klass = send(association_id)
+
+ klass.send("#{method}_#{name}", *params)
+ end
+ end
+
+ end
before_callback = <<-end_eval
init_inherited_assoc("#{association_id}")
@@ -53,23 +82,6 @@ def self.inherits_from(association_id, options = {})
before_update(before_callback)
end
- # Creates a proxy accessor method for an inherited object.
- def self.alias_associated_attr(association_id, name)
- define_method(name) do
- init_inherited_assoc(association_id)
- klass = send(association_id)
-
- klass.send(name)
- end
-
- define_method("#{name}=") do |new_value|
- init_inherited_assoc(association_id)
- klass = send(association_id)
-
- klass.send("#{name}=", new_value)
- end
- end
-
private
# Ensures that there is an association to access, if not, creates one.
def init_inherited_assoc(association_id)

0 comments on commit 71c5092

Please sign in to comment.