Class: Dry::Monads::Maybe::Some

Inherits:
Dry::Monads::Maybe show all
Includes:
RightBiased::Right
Defined in:
lib/dry/monads/maybe.rb,
lib/dry/monads/result.rb

Overview

Represents a value that is present, i.e. not nil.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from RightBiased::Right

#===, #and, #apply, #bind, #deconstruct, #deconstruct_keys, #discard, #flatten, included, #or, #or_fmap, #tee, #value!, #value_or

Methods inherited from Dry::Monads::Maybe

#as_json, coerce, json_create, #monad, #none?, pure, #some?, #to_json, #to_maybe, #to_monad, to_proc

Methods included from Transformer

#fmap2, #fmap3

Constructor Details

#initialize(value = Undefined) ⇒ Some

Returns a new instance of Some.

Raises:

  • (ArgumentError)


105
106
107
108
# File 'lib/dry/monads/maybe.rb', line 105

def initialize(value = Undefined)
  raise ArgumentError, 'nil cannot be some' if value.nil?
  @value = Undefined.default(value, Unit)
end

Class Method Details

.[](*value) ⇒ Object

Shortcut for Some([...])

@example include Dry::Monads[:maybe]

def call Some[200, {}, ['ok']] # => Some([200, {}, ['ok']]) end



101
102
103
# File 'lib/dry/monads/maybe.rb', line 101

def self.[](*value)
  new(value)
end

Instance Method Details

#fmap(*args, &block) ⇒ Maybe::Some, Maybe::None Also known as: maybe

Does the same thing as #bind except it also wraps the value in an instance of Maybe::Some monad. This allows for easier chaining of calls.

Examples:

Dry::Monads.Some(4).fmap(&:succ).fmap(->(n) { n**2 }) # => Some(25)

Parameters:

  • args (Array<Object>)

    arguments will be transparently passed through to #bind

Returns:

  • (Maybe::Some, Maybe::None)

    Wrapped result, i.e. nil will be mapped to None, other values will be wrapped with Some



120
121
122
# File 'lib/dry/monads/maybe.rb', line 120

def fmap(*args, &block)
  Maybe.coerce(bind(*args, &block))
end

#to_result(fail = Unit, &block) ⇒ Success<Any>

Converts to Sucess(value!)

Parameters:

  • fail (#call) (defaults to: Unit)

    Fallback value

  • block (Proc)

    Fallback block

Returns:



389
390
391
# File 'lib/dry/monads/result.rb', line 389

def to_result(fail = Unit, &block)
  Result::Success.new(@value)
end

#to_sString Also known as: inspect

Returns:

  • (String)


126
127
128
129
130
131
132
# File 'lib/dry/monads/maybe.rb', line 126

def to_s
  if Unit.equal?(@value)
    'Some()'
  else
    "Some(#{@value.inspect})"
  end
end