Module: Ytry::Try
Class Method Summary collapse
Instance Method Summary collapse
- #each {|self.get| ... } ⇒ Object
- #flat_map(&block) ⇒ Object
- #flatten ⇒ Object
- #get_or_else ⇒ Object
- #grep(pattern, &block) ⇒ Object
- #inspect ⇒ Object
- #or_else ⇒ Object
- #zip(*others) ⇒ Object
- #|(lambda) ⇒ Object
Class Method Details
.ary_to_type(value) ⇒ Object
14 15 16 17 18 19 20 |
# File 'lib/ytry.rb', line 14 def self.ary_to_type value raise Try.invalid_argument('Argument must be an array-like object', value) unless value.respond_to? :to_ary return value if value.is_a? Try value.to_ary.empty? ? Failure.new(RuntimeError.new("Element not found").tap{|ex| ex.set_backtrace(caller)}) : Success.new(value.to_ary.first) end |
.zip(*try_array) ⇒ Object
21 22 23 24 |
# File 'lib/ytry.rb', line 21 def self.zip *try_array first_failure = try_array.find(&:empty?) first_failure.nil? ? Success.new(try_array.map(&:get)) : first_failure end |
Instance Method Details
#each {|self.get| ... } ⇒ Object
25 26 27 28 29 |
# File 'lib/ytry.rb', line 25 def each return enum_for(__method__) unless block_given? yield self.get unless empty? return self end |
#flat_map(&block) ⇒ Object
36 37 38 39 40 41 42 |
# File 'lib/ytry.rb', line 36 def flat_map &block block or return enum_for(method) return self if self.empty? wrapped_result = Try{block.call(self.get)} return wrapped_result if (!wrapped_result.empty? && !wrapped_result.get.respond_to?(:to_ary)) Try.ary_to_type(wrapped_result.flatten) end |
#flatten ⇒ Object
46 47 48 49 |
# File 'lib/ytry.rb', line 46 def flatten return self if empty? Try.ary_to_type self.get end |
#get_or_else ⇒ Object
61 62 63 64 65 |
# File 'lib/ytry.rb', line 61 def get_or_else raise ArgumentError, 'missing block' unless block_given? return self.get unless empty? yield end |
#grep(pattern, &block) ⇒ Object
43 44 45 |
# File 'lib/ytry.rb', line 43 def grep(pattern, &block) self.empty? ? self : Try.ary_to_type(Try{super}.flatten) end |
#inspect ⇒ Object
66 |
# File 'lib/ytry.rb', line 66 def inspect() to_s end |
#or_else ⇒ Object
56 57 58 59 60 |
# File 'lib/ytry.rb', line 56 def or_else return self unless empty? other = yield other.is_a?(Try) ? other : raise(Try.invalid_argument('Block should evaluate to an Try', other)) end |
#zip(*others) ⇒ Object
50 51 52 |
# File 'lib/ytry.rb', line 50 def zip *others Try.zip(self, *others) end |
#|(lambda) ⇒ Object
53 54 55 |
# File 'lib/ytry.rb', line 53 def | lambda self.flat_map &lambda # slow but easy to read + supports symbols out of the box end |