Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Use symbols in case statements for great justice #5706

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+48 −0
Split
@@ -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,28 @@
+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?
+ clause = 'not-true'
+ when ~:so_true?
+ clause = 'so-true'
+ else
+ clause = 'else'
+ end
+
+ assert_equal 'so-true', clause
+ end
+end