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
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
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
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
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
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
Private Instance Methods
# File lib/direct.rb, line 122 def __directions @__directions ||= Direct::Group.new end
# File lib/direct.rb, line 118 def allow_missing_directions? false end