Permalink
Browse files

dry up some duplicated code

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@5883 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information...
1 parent 0d34c28 commit 8dd08f98c7f8d78c4b75e4d4c231d7341915f797 @jamis jamis committed Jan 11, 2007
Showing with 21 additions and 37 deletions.
  1. +21 −37 activerecord/lib/active_record/associations/has_one_association.rb
@@ -7,47 +7,15 @@ def initialize(owner, reflection)
end
def create(attrs = {}, replace_existing = true)
- # make sure we load the target first, if we plan on replacing the existing
- # instance. Otherwise, if the target has not previously been loaded
- # elsewhere, the instance we create will get orphaned.
- load_target if replace_existing
- record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create(attrs) }
-
- if replace_existing
- replace(record, true)
- else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
- self.target = record
- end
-
- record
+ new_record(replace_existing) { |klass| klass.create(attrs) }
end
def create!(attrs = {}, replace_existing = true)
- load_target if replace_existing
- record = @reflection.klass.with_scope(:create => construct_scope[:create]) { @reflection.klass.create!(attrs) }
-
- if replace_existing
- replace(record, true)
- else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
- self.target = record
- end
-
- record
+ new_record(replace_existing) { |klass| klass.create!(attrs) }
end
- def build(attributes = {}, replace_existing = true)
- record = @reflection.klass.new(attributes)
-
- if replace_existing
- replace(record, true)
- else
- record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
- self.target = record
- end
-
- record
+ def build(attrs = {}, replace_existing = true)
+ new_record(replace_existing) { |klass| klass.new(attrs) }
end
def replace(obj, dont_save = false)
@@ -106,7 +74,23 @@ def construct_scope
set_belongs_to_association_for(create_scoping)
{ :create => create_scoping }
end
-
+
+ def new_record(replace_existing)
+ # make sure we load the target first, if we plan on replacing the existing
+ # instance. Otherwise, if the target has not previously been loaded
+ # elsewhere, the instance we create will get orphaned.
+ load_target if replace_existing
+ record = @reflection.klass.with_scope(:create => construct_scope[:create]) { yield @reflection.klass }
+
+ if replace_existing
+ replace(record, true)
+ else
+ record[@reflection.primary_key_name] = @owner.id unless @owner.new_record?
+ self.target = record
+ end
+
+ record
+ end
end
end
end

0 comments on commit 8dd08f9

Please sign in to comment.