Skip to content

Instantly share code, notes, and snippets.

@marzdrel
Last active January 22, 2017 13:55
Show Gist options
  • Save marzdrel/eae85f62b4f3f07e0d9d700e3633882e to your computer and use it in GitHub Desktop.
Save marzdrel/eae85f62b4f3f07e0d9d700e3633882e to your computer and use it in GitHub Desktop.
# 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