Skip to content

Commit

Permalink
bug 1108: yield to block provided to find_or_create_by_x
Browse files Browse the repository at this point in the history
Starting in 2.3.8 we stopped yielding to blocks passed in to
find_or_create_by_x methods.  This patch restores that behavior and
adds a case to test it.
  • Loading branch information
ccabot authored and tenderlove committed Oct 21, 2010
1 parent fdfc8e3 commit bdfddb0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
Expand Up @@ -375,17 +375,17 @@ def load_target
target
end

def method_missing(method, *args)
def method_missing(method, *args, &block)
case method.to_s
when 'find_or_create'
return find(:first, :conditions => args.first) || create(args.first)
when /^find_or_create_by_(.*)$/
rest = $1
find_args = pull_finder_args_from(DynamicFinderMatch.match(method).attribute_names, *args)
return send("find_by_#{rest}", find_args) ||
method_missing("create_by_#{rest}", *args)
method_missing("create_by_#{rest}", *args, &block)
when /^create_by_(.*)$/
return create($1.split('_and_').zip(args).inject({}) { |h,kv| k,v=kv ; h[k] = v ; h })
return create($1.split('_and_').zip(args).inject({}) { |h,kv| k,v=kv ; h[k] = v ; h }, &block)
end

if @target.respond_to?(method) || (!@reflection.klass.respond_to?(method) && Class.respond_to?(method))
Expand Down
Expand Up @@ -82,6 +82,12 @@ def test_find_or_create_by_with_additional_parameters
assert_equal 4, post.comments.length
end

def test_find_or_create_by_with_block
post = Post.create! :title => 'test_find_or_create_by_with_additional_parameters', :body => 'this is the body'
comment = post.comments.find_or_create_by_body('other test comment body') { |comment| comment.type = 'test' }
assert_equal 'test', comment.type
end

def test_find_or_create
person = Person.create! :first_name => 'tenderlove'
post = Post.find :first
Expand Down

0 comments on commit bdfddb0

Please sign in to comment.