Last active
January 22, 2017 13:55
-
-
Save marzdrel/eae85f62b4f3f07e0d9d700e3633882e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Little functional quirk to replace a CASE statement, when you first query an object | |
# and call a method to command an action. You can pass a block at the end for an ELSE | |
# statement. | |
# | |
# Usage: | |
# | |
# Func.switch order, | |
# available?: -> { order.submit }, | |
# returned?: -> { order.cancel } | |
# | |
# Func.switch order, | |
# available?: :submit, | |
# returned?: :cancel | |
# | |
# if object.available? | |
# object.submit | |
# elsif object.returned? | |
# object.cancel | |
# end | |
class Func | |
def self.switch(object, hash) | |
hash.each do |method, func| | |
next unless object.public_send(method) | |
return case func | |
when Symbol | |
object.public_send(func) | |
when Proc | |
func.() | |
else | |
raise ArgumentError | |
end | |
end | |
yield if block_given? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment