Permalink
Browse files

Syntactic sugar for using symbols in case statements

  • Loading branch information...
1 parent 87b30fb commit 731bc3d61b7a745af53b402169dae5abcefe49f2 Amiel Martin committed Mar 26, 2012
Showing with 47 additions and 0 deletions.
  1. +20 −0 activesupport/lib/active_support/core_ext/symbol.rb
  2. +27 −0 activesupport/test/core_ext/symbol_test.rb
@@ -0,0 +1,20 @@
+class Symbol
+
+ # Unary ~ provides syntactic sugar for case statements. Examples:
+ #
+ # case user
+ # when ~:admin?
+ # # Do stuff
+ # when ~:active?
+ # # Do stuff
+ # end
+ #
+ # Would be equivalent to:
+ #
+ # if user.admin?
+ # # Do stuff
+ # elsif user.active?
+ # # Do stuff
+ # end
+ alias_method :~, :to_proc
+end
@@ -0,0 +1,27 @@
+require 'abstract_unit'
+require 'active_support/core_ext/symbol'
+
+class SymbolTests < ActiveSupport::TestCase
+
+ class ExamplePredicateClass
+ def so_true?
+ true
+ end
+
+ def not_true?
+ false
+ end
+ end
+
+ def test_tilde_operator_in_case
+ case ExamplePredicateClass.new
+ when ~:not_true?
+ fail 'Reached not_true? clause'
+ when ~:so_true?
+ pass
+ else
+ fail 'Reached else clause'
+ end
+ end
+
+end

0 comments on commit 731bc3d

Please sign in to comment.