Module: Ytry::Try
Class Method Summary collapse
Instance Method Summary collapse
- #each(&block) ⇒ 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("Could not convert empty array-like object to Success")) : Success.new(value.to_ary.first) end |
Instance Method Details
#each(&block) ⇒ Object
21 22 23 |
# File 'lib/ytry.rb', line 21 def each &block to_ary.each &block end |
#flat_map(&block) ⇒ Object
30 31 32 33 34 35 36 |
# File 'lib/ytry.rb', line 30 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
40 41 42 43 |
# File 'lib/ytry.rb', line 40 def flatten return self if empty? Try.ary_to_type self.get end |
#get_or_else ⇒ Object
58 59 60 61 62 |
# File 'lib/ytry.rb', line 58 def get_or_else raise ArgumentError, 'missing block' unless block_given? return self.get unless empty? yield end |
#grep(pattern, &block) ⇒ Object
37 38 39 |
# File 'lib/ytry.rb', line 37 def grep(pattern, &block) Try.ary_to_type super end |
#inspect ⇒ Object
63 |
# File 'lib/ytry.rb', line 63 def inspect() to_s end |
#or_else ⇒ Object
53 54 55 56 57 |
# File 'lib/ytry.rb', line 53 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
44 45 46 47 48 49 |
# File 'lib/ytry.rb', line 44 def zip *others # TODO return first Failure among arguments - if any return Failure.new(Exception.new) if self.empty? || others.any?(&:empty?) collection = others.reduce(self.to_a, &:concat) Success.new collection end |
#|(lambda) ⇒ Object
50 51 52 |
# File 'lib/ytry.rb', line 50 def | lambda self.flat_map &lambda # slow but easy to read + supports symbols out of the box end |