module Direct

Include this module in your classes to provide a way for your objects to handle named scenarios with blocks of code.

Constants

VERSION

Public Class Methods

allow_missing_directions() click to toggle source

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.
# File lib/direct.rb, line 29
def self.allow_missing_directions
  AllowMissing
end
defer(*args, object: nil, &block) click to toggle source

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
# File lib/direct.rb, line 71
def self.defer(*args, object: nil, &block)
  Executable.new(*args, object: object, &block)
end
strict_defer(&block) click to toggle source

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
# File lib/direct.rb, line 55
def self.strict_defer(&block)
  StrictExecutable.new(&block)
end

Public Instance Methods

as_directed(key, *args) click to toggle source

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

# 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) click to toggle source

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.

# File lib/direct.rb, line 90
def direct(key, callable=nil, &block)
  __directions.store(key, callable || block)
  self
end
Also aliased as: when
when(key, callable=nil, &block)
Alias for: direct

Private Instance Methods

__directions() click to toggle source
# File lib/direct.rb, line 122
def __directions
  @__directions ||= Direct::Group.new
end
allow_missing_directions?() click to toggle source
# File lib/direct.rb, line 118
def allow_missing_directions?
  false
end