Skip to content

Commit

Permalink
Pass the right binding when string is passed to :if with validations.…
Browse files Browse the repository at this point in the history
… [caspercg] Closes #9300

git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@7365 5ecf4fe2-1ee6-0310-87b1-e25e094e27de
  • Loading branch information
NZKoz committed Aug 28, 2007
1 parent 93eaaef commit 5840108
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
2 changes: 1 addition & 1 deletion activerecord/lib/active_record/validations.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ def condition_block?(condition)
def evaluate_condition(condition, record) def evaluate_condition(condition, record)
case condition case condition
when Symbol: record.send(condition) when Symbol: record.send(condition)
when String: eval(condition, binding) when String: eval(condition, record.send(:binding))
else else
if condition_block?(condition) if condition_block?(condition)
condition.call(record) condition.call(record)
Expand Down
22 changes: 22 additions & 0 deletions activerecord/test/validations_test.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -1127,6 +1127,28 @@ def test_validation_order
assert !t.valid? assert !t.valid?
assert_equal "can't be blank", t.errors.on("title").first assert_equal "can't be blank", t.errors.on("title").first
end end

# previous implementation of validates_presence_of eval'd the
# string with the wrong binding, this regression test is to
# ensure that it works correctly
def test_validation_with_if_as_string
Topic.validates_presence_of(:title)
Topic.validates_presence_of(:author_name, :if => "title.to_s.match('important')")

t = Topic.new
assert !t.valid?, "A topic without a title should not be valid"
assert !t.errors.invalid?("author_name"), "A topic without an 'important' title should not require an author"

t.title = "Just a title"
assert t.valid?, "A topic with a basic title should be valid"

t.title = "A very important title"
assert !t.valid?, "A topic with an important title, but without an author, should not be valid"
assert t.errors.invalid?("author_name"), "A topic with an 'important' title should require an author"

t.author_name = "Hubert J. Farnsworth"
assert t.valid?, "A topic with an important title and author should be valid"
end
end end




Expand Down

0 comments on commit 5840108

Please sign in to comment.