aboutsummaryrefslogtreecommitdiffstats
path: root/lib/result.rb
blob: 96e03d32303bc5e5254d4a7d56f3bc7daf29388e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# A value wrapper adding status information to any value
# Status can be :ok or :error, we are thusly implementing
# what is expressed in Elixir/Erlang as result tuples and
# in Haskell as `Data.Either`
class Result

  attr_reader :status, :value
  
  class << self
    def ok value
      make :ok, value
    end
    def error value
      make :error, value
    end

    def new *args
      raise NoMethodError, "No default constructor for #{self}"
    end

    private
    def make status, value
      allocate.tap do | o |
        o.instance_exec do
          @status = status
          @value  = value
        end
      end
    end
  end

  def ok?; status == :ok end

  def == other
    other.kind_of?(self.class) && other.status == status && other.value == value
  end
end