Module: Direct

Included in:
AllowMissing, StrictExecutable
Defined in:
lib/direct.rb,
lib/direct.rb,
lib/direct/group.rb,
lib/direct/version.rb,
lib/direct/executable.rb,
lib/direct/strict_executable.rb

Overview

your objects to handle named scenarios with blocks of code.

Defined Under Namespace

Modules: AllowMissing Classes: Executable, Group, MissingProcedure, StrictExecutable

Constant Summary collapse

VERSION =
"2.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.allow_missing_directionsObject

Use this module to allow your procedures to go ignored.

Example:

class Thing < ActiveRecord::Base
  include Direct.allow_missing_directions

  def save(*)
    super
    as_directed(:success)
  end
end

Thing.new.save # => no MissingProcedure error raised.


29
30
31
# File 'lib/direct.rb', line 29

def self.allow_missing_directions
  AllowMissing
end

.defer(*args, object: nil, &block) ⇒ Object

Wrap a block of code to return an object for handling success or failure.

Example:

def do_it
  Direct.defer{
    [true, false].sample
  }
end
do_it.value


71
72
73
# File 'lib/direct.rb', line 71

def self.defer(*args, object: nil, &block)
  Executable.new(*args, object: object, &block)
end

.strict_defer(&block) ⇒ Object

Wrap a block of code to return an object for handling success or failure. Raises exceptions when directions are not provided

Example:

def do_it
  Direct.strict_defer{
    [true, false].sample
  }
end
do_it.
  success{|result| puts "it worked!" }.
  failure{|result| puts "it failed!" }.
  value


55
56
57
# File 'lib/direct.rb', line 55

def self.strict_defer(&block)
  StrictExecutable.new(&block)
end

Instance Method Details

#as_directed(key, *args) ⇒ Object

Perform the named block of code

def do_it

# do things here
as_directed(:success, "success", "messages")

rescue => e

as_directed(:failure, errors)

end

This will raise an error if the provided key is not found



106
107
108
109
110
111
112
113
114
# File 'lib/direct.rb', line 106

def as_directed(key, *args)
  return if allow_missing_directions? && __directions.empty?
  __directions.fetch(key).map do |block|
    block.call(self, *args)
  end
rescue KeyError
  return if allow_missing_directions?
  raise MissingProcedure, "Procedure for :#{key} was reached but not specified."
end

#direct(key, callable = nil, &block) ⇒ Object Also known as: when

Tell the object what to do in a given scenario.

object.direct(:success){|obj| puts “it worked!” } object.direct(:failure){|obj| puts “it failed!” }

You may also chain calls to this method

object.direct(:success){ |obj|

puts "it worked!"

}.direct(:failure){ |obj|

puts "it failed!"

}.do_it

Your blocks will always receive the object itself as the first argument.



90
91
92
93
# File 'lib/direct.rb', line 90

def direct(key, callable=nil, &block)
  __directions.store(key, callable || block)
  self
end