Permalink
Browse files

Added Object#present_in to simplify value whitelisting

  • Loading branch information...
1 parent 5d03781 commit 4edca106daacc5a159289eae255207d160f22396 @dhh dhh committed Feb 18, 2014
@@ -2,6 +2,18 @@
*Xavier Noria*
+* Added Object#present_in to simplify value whitelisting.
+
+ Before:
+
+ params[:bucket_type].in?(%w( project calendar )) ? params[:bucket_type] : nil
+
+ After:
+
+ params[:bucket_type].present_in %w( project calendar )
+
+ *DHH*
+
* Fix the implementation of Multibyte::Unicode.tidy_bytes for JRuby
The existing implementation caused JRuby to raise the error:
@@ -12,4 +12,16 @@ def in?(another_object)
rescue NoMethodError
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end
+
+ # Returns the receiver if it's included in the argument otherwise returns +nil+.
+ # Argument must be any object which responds to +#include?+. Usage:
+ #
+ # params[:bucket_type].present_in %w( project calendar )
+ #
+ # This will throw an ArgumentError if the argument doesn't respond to +#include?+.
+ #
+ # @return [Object]
+ def present_in(another_object)
+ self.in?(another_object) ? self : nil
+ end
end
@@ -47,4 +47,9 @@ def test_in_module
def test_no_method_catching
assert_raise(ArgumentError) { 1.in?(1) }
end
+
+ def test_present_in
+ assert_equal "stuff", "stuff".present_in(%w( lots of stuff ))
+ assert_not "stuff".present_in(%w( lots of crap ))
@arthurnn
arthurnn Feb 18, 2014 Member

Should in here be assert_nil instead?

@dhh
dhh via email Feb 18, 2014 Member
+ end
end

3 comments on commit 4edca10

@piersadrian

Since this is essentially the 'inclusion' form of Object#presence, wouldn't this method's name be more consistent if it were named presence_in?

The present_in name sounds very much like Object#present?, and while present_in isn't interrogative, it still sounds like it would return a boolean, like present?, rather than self, like presence.

Thanks for this!

@dhh
Member
dhh commented on 4edca10 Feb 23, 2014
@dhh
Member
dhh commented on 4edca10 Feb 24, 2014
Please sign in to comment.