diff --git a/Gemfile.lock b/Gemfile.lock index e61a313..5071f64 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - errgonomic (0.5.1) + errgonomic (0.6.0) concurrent-ruby (~> 1.0) GEM @@ -303,4 +303,4 @@ DEPENDENCIES yard-doctest (~> 0.1) BUNDLED WITH - 2.6.9 + 2.6.6 diff --git a/gemset.nix b/gemset.nix index 52b79ff..d5b8ebb 100644 --- a/gemset.nix +++ b/gemset.nix @@ -269,7 +269,7 @@ path = ./.; type = "path"; }; - version = "0.5.1"; + version = "0.6.0"; }; erubi = { groups = ["default" "development"]; diff --git a/lib/errgonomic/result.rb b/lib/errgonomic/result.rb index 97df1e7..6c00fc8 100644 --- a/lib/errgonomic/result.rb +++ b/lib/errgonomic/result.rb @@ -250,6 +250,17 @@ def map(&block) Ok(block.call(value)) end + # Map the Err(e) to an Err(f), preserving the Ok + # + # @example + # Ok(:Alice).map_err { |_e| :Bob } # => Ok(:Alice) + # Err(:bob).map_err { |e| e.capitalize } # => Err(:Bob) + def map_err(&block) + return self if ok? + + Err(block.call(value)) + end + # Refuse to serialize an unwrapped Result as a String. Results must be # correctly handled to access their inner value. # @@ -271,6 +282,30 @@ def to_s def to_json(*_args) raise Errgonomic::SerializeError, 'cannot serialize an unwrapped Result' end + + # @example simple pattern match with variable capture of the value + # result = Errgonomic::Result::Ok.new(1) + # case result + # in Errgonomic::Result::Ok, value + # "Measurement is #{value}" + # in Errgonomic::Result::Err, err + # "Measurement is not available" + # end # => "Measurement is 1" + # + # @example more advanced pattern match against the kind of value + # result = Errgonomic::Result::Err.new(StandardError.new("nope")) + # case result + # in Errgonomic::Result::Ok, value + # "Measurement is #{value}" + # in Errgonomic::Result::Err, String => msg + # "Measurement failed with a message: #{msg}" + # in Errgonomic::Result::Err, Exception => e + # "Measurement produced an exception -- #{e.class}: #{e}" + # end # => "Measurement produced an exception -- StandardError: nope" + def deconstruct + [self, value] + end + end # The Ok variant. diff --git a/lib/errgonomic/version.rb b/lib/errgonomic/version.rb index 0e9768e..35d20d5 100644 --- a/lib/errgonomic/version.rb +++ b/lib/errgonomic/version.rb @@ -1,5 +1,5 @@ # frozen_string_literal: true module Errgonomic - VERSION = '0.5.1' + VERSION = '0.6.0' end