Module: Operate::Command

Includes:
Pubsub::Publisher
Defined in:
lib/operate/command.rb

Overview

A command-pattern implementation for controller actions, etc.

‘register` handlers with on(). `broadcast` results with broadcast(). `transaction` wraps ActiveRecord transactions. `expose` to set a value from the handler block to the caller

Defined Under Namespace

Modules: ClassMethods Classes: Error

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Pubsub::Publisher

#broadcast, #on

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/operate/command.rb', line 51

def method_missing(method_name, *args, &block)
  if @caller.respond_to?(method_name, true)
    @caller.send(method_name, *args, &block)
  else
    super
  end
end

Class Method Details

.included(target) ⇒ Object



16
17
18
# File 'lib/operate/command.rb', line 16

def self.included(target)
  target.extend ClassMethods
end

Instance Method Details

#evaluate(&block) ⇒ Object



46
47
48
49
# File 'lib/operate/command.rb', line 46

def evaluate(&block)
  @caller = eval('self', block.binding)
  instance_eval(&block)
end

#expose(presentation_data) ⇒ Object

Expose a value within a handler block to the caller. Sets attribute directly if available, or as an instance variable.

RegisterAccount.call(@form) do

on(:ok) { |user| expose(:user => user) }

end



71
72
73
74
75
76
77
78
79
# File 'lib/operate/command.rb', line 71

def expose(presentation_data)
  presentation_data.each do |attribute, value|
    if @caller.respond_to?("#{attribute}=")
      @caller.public_send("#{attribute}=", value)
    else
      @caller.instance_variable_set("@#{attribute}", value)
    end
  end
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/operate/command.rb', line 59

def respond_to_missing?(method_name, include_private = false)
  @caller.respond_to?(method_name, include_private)
end

#transaction(&block) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/operate/command.rb', line 36

def transaction(&block)
  return unless block_given?

  if defined?(ActiveRecord)
    ::ActiveRecord::Base.transaction(&block)
  else
    raise Error, 'Transactions are supported only with ActiveRecord'
  end
end