Skip to content

Instantly share code, notes, and snippets.

@alebian
Created June 23, 2020 01:30
Show Gist options
  • Save alebian/548a23e601fd73792bcaf352515a5391 to your computer and use it in GitHub Desktop.
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
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