Skip to content

Commit 4edca10

Browse files
author
David Heinemeier Hansson
committed
Added Object#present_in to simplify value whitelisting
1 parent 5d03781 commit 4edca10

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

activesupport/CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,18 @@
22

33
*Xavier Noria*
44

5+
* Added Object#present_in to simplify value whitelisting.
6+
7+
Before:
8+
9+
params[:bucket_type].in?(%w( project calendar )) ? params[:bucket_type] : nil
10+
11+
After:
12+
13+
params[:bucket_type].present_in %w( project calendar )
14+
15+
*DHH*
16+
517
* Fix the implementation of Multibyte::Unicode.tidy_bytes for JRuby
618

719
The existing implementation caused JRuby to raise the error:

activesupport/lib/active_support/core_ext/object/inclusion.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,16 @@ def in?(another_object)
1212
rescue NoMethodError
1313
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
1414
end
15+
16+
# Returns the receiver if it's included in the argument otherwise returns +nil+.
17+
# Argument must be any object which responds to +#include?+. Usage:
18+
#
19+
# params[:bucket_type].present_in %w( project calendar )
20+
#
21+
# This will throw an ArgumentError if the argument doesn't respond to +#include?+.
22+
#
23+
# @return [Object]
24+
def present_in(another_object)
25+
self.in?(another_object) ? self : nil
26+
end
1527
end

activesupport/test/core_ext/object/inclusion_test.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,4 +47,9 @@ def test_in_module
4747
def test_no_method_catching
4848
assert_raise(ArgumentError) { 1.in?(1) }
4949
end
50+
51+
def test_present_in
52+
assert_equal "stuff", "stuff".present_in(%w( lots of stuff ))
53+
assert_not "stuff".present_in(%w( lots of crap ))
54+
end
5055
end

0 commit comments

Comments
 (0)