Class: ResultPicker

Inherits:
Object
  • Object
show all
Defined in:
lib/result_picker.rb

Overview

Result picker was designed to simply yield return value before the block ends My own use case was returning model built inside transaction, which could be rolled back because it was invalid. Normally, solution is

x = nil
something do
  stuff
  x = value
  more_stuff
end
x

which is ugly. The better idea is to wrap this stuff inside one of your methods e.g. `synchronize`, `transaction`, and this class allows you to DRY

Usage:

ResultPicker.pick! do |result_picker|
  something do
    stuff
    result_picker.call value
    more_stuff
  end
end

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#result(default = nil) ⇒ Object


59
60
61
62
# File 'lib/result_picker.rb', line 59

def result(default = nil)
  return default unless result_given?
  @result
end

Class Method Details

.pick(strict = false) ⇒ Object

This is all in one method which will pass lambda into the block and then execute it, assuming this is default value to return if lambda would not be called inside

Raises:

  • (ArgumentError)

31
32
33
34
35
36
# File 'lib/result_picker.rb', line 31

def self.pick(strict = false)
  raise ArgumentError, 'block not given' unless block_given?
  picker = new
  x = yield picker.lambda
  strict ? picker.result! : picker.result(x)
end

.pick!(&block) ⇒ Object

This is all in one method which will pass lambda into the block and then execute it

Raises:

  • (ResultNotGiven)

    if lambda was not called


42
43
44
# File 'lib/result_picker.rb', line 42

def self.pick!(&block)
  pick(true, &block)
end

Instance Method Details

#lambdaProc


47
48
49
50
# File 'lib/result_picker.rb', line 47

def lambda
  context = self
  -> (x) { context.result = x }
end

#result!Object

Returns stored result

Raises:

  • (ResultNotGiven)

    if lambda was not called


66
67
68
69
# File 'lib/result_picker.rb', line 66

def result!
  raise ResultNotGiven unless result_given?
  @result
end

#result_given?bool


53
54
55
# File 'lib/result_picker.rb', line 53

def result_given?
  defined?(@result)
end