module Maybe

Maybe is a union type that is expressed in terms of Nothing and Just. It is useful for gracefully handling potentially null values:

@example when value is non-null

User.create!(email: "john@doe.com", name: "John Doe")

Maybe
  .from_nullable(User.find_by(email: "john@doe.com"))
  .map {|user| user.name }
  .get_or_else { "NO NAME" }

#=> "John Doe"

@example when value is null

Maybe
  .from_nullable(User.find_by(email: "not@present.com"))
  .map {|user| user.name }
  .get_or_else { "NO NAME" }

#=> "NO NAME"

Constants

C

Public Class Methods

Just(value) click to toggle source
# File lib/maybe.rb, line 66
def self.Just(value)
  Just.new(value)
end
Nothing() click to toggle source
# File lib/maybe.rb, line 53
def self.Nothing
  Nothing.instance
end
from_nullable(value) click to toggle source
# File lib/maybe.rb, line 101
def self.from_nullable(value)
  value.nil? ? Nothing.instance : Just.new(value)
end
lift(f, fst, *rst) click to toggle source
# File lib/maybe.rb, line 170
def self.lift(f, fst, *rst)
  [fst, *rst]
    .reduce(Just([])) {|accum, maybe|
      accum.flat_map {|accum_|
        maybe.map {|maybe_| accum_ + [maybe_] }
      }
    }
    .ap( Just(->(args){ f.call(*args) }) )
end
of(value) click to toggle source
# File lib/maybe.rb, line 79
def self.of(value)
  Just.new(value)
end
zip(fst, snd, *rest) click to toggle source
# File lib/maybe.rb, line 131
def self.zip(fst, snd, *rest)
  [fst, snd, *rest].reduce(Just([])) do |accum, maybe|
    accum.flat_map do |accum_|
      maybe.map {|maybe_| accum_ + [maybe_] }
    end
  end
end