Created
June 23, 2020 01:30
-
-
Save alebian/548a23e601fd73792bcaf352515a5391 to your computer and use it in GitHub Desktop.
Result object to use in case statements similar to Elixirs pattern matching for standard library
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
class Result | |
def initialize(options = {}) | |
@success = options[:success] || false | |
@error = options[:error] | |
@result = options[:result] | |
end | |
def success? | |
@success | |
end | |
end | |
module SymbolExtensions | |
def ===(other) | |
if other.is_a?(Result) | |
if other.success? | |
return true if self == :ok | |
else | |
return true if self == :error | |
end | |
false | |
else | |
super | |
end | |
end | |
end | |
class Symbol | |
prepend SymbolExtensions | |
end | |
successful = Result.new(success: true) | |
wrong = Result.new(success: false) | |
res = wrong | |
case res | |
when :ok | |
puts "Everything worked fine" | |
when :error | |
puts "There was an error" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment