Skip to content

Commit 9b11429

Browse files
committed
feat: add from_or from_or! methods to Result
1 parent 8a83fda commit 9b11429

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

spec/result_spec.cr

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,4 +217,20 @@ describe Result do
217217
y = Err(Int32, String)["foo"]
218218
y.unwrap_or_else { |e| e.size }.should eq(3)
219219
end
220+
221+
it "from" do
222+
Result.from_or("error", true).should eq(Ok(Bool, String)[true])
223+
Result.from_or("error", false).should eq(Err(Bool, String)["error"])
224+
225+
Result(String, Bool).from_or?(false, ENV["USER"]?).should eq(Ok(String, Bool)[%x(whoami).chomp])
226+
Result(String, Bool).from_or?(false, ENV["NOT_EXISTING"]?).should eq(Err(String, Bool)[false])
227+
228+
Result.from_or!(false) { ENV["USER"] }.should eq(Ok(String, Bool)[%x(whoami).chomp])
229+
Result.from_or!(false) { ENV["NOT_EXISTING"] }.should eq(Err(String, Bool)[false])
230+
231+
env_user = -> { ENV["USER"] }
232+
env_not_existing = -> { ENV["NOT_EXISTING"] }
233+
Result.from_or!(false, env_user).should eq(Ok(String, Bool)[%x(whoami).chomp])
234+
Result.from_or!(false, env_not_existing).should eq(Err(String, Bool)[false])
235+
end
220236
end

src/result.cr

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,26 @@ abstract struct Result(T, E)
270270
{% end %}
271271
end
272272
end
273+
274+
def self.from_or(error : E, value : T) : Result(T, E)
275+
value ? Ok(T, E).new(value) : Err(T, E).new(error)
276+
end
277+
278+
def self.from_or?(error : E, value : T | Nil) : Result(T, E)
279+
value ? Ok(T, E).new(value) : Err(T, E).new(error)
280+
end
281+
282+
def self.from_or!(error : E, &block : -> T) : Result(T, E)
283+
Ok(T, E).new(block.call)
284+
rescue
285+
Err(T, E).new(error)
286+
end
287+
288+
def self.from_or!(error : E, block : -> T) : Result(T, E)
289+
Ok(T, E).new(block.call)
290+
rescue
291+
Err(T, E).new(error)
292+
end
273293
end
274294

275295
struct Ok(T, E) < Result(T, E)

0 commit comments

Comments
 (0)