Module: Surrounded::Context::TriggerControls

Defined in:
lib/surrounded/context/trigger_controls.rb

Instance Method Summary collapse

Instance Method Details

#convert_method_to_trigger(name) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/surrounded/context/trigger_controls.rb', line 44

def convert_method_to_trigger(name)
  unless triggers.include?(name) || name.nil?
    alias_method :"__trigger_#{name}", :"#{name}"
    private :"__trigger_#{name}"
    remove_method :"#{name}"
    define_trigger(name)
    store_trigger(name)
  end
end

#define_trigger(name) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/surrounded/context/trigger_controls.rb', line 54

def define_trigger(name)
  class_eval <<~MOD, __FILE__, __LINE__ + 1
    def #{name}(...)
      begin
        apply_behaviors

        #{trigger_return_content(name)}

      ensure
        remove_behaviors
      end
    end
  MOD
end

#define_trigger_action(*name_and_args, &block) ⇒ Object



77
78
79
# File 'lib/surrounded/context/trigger_controls.rb', line 77

def define_trigger_action(*name_and_args, &block)
  trigger_action_module.send(:define_method, *name_and_args, &block)
end

#store_trigger(*names) ⇒ Object



11
12
13
# File 'lib/surrounded/context/trigger_controls.rb', line 11

def store_trigger(*names)
  @triggers.merge(names)
end

#trigger(*names, &block) ⇒ Object

Creates a context instance method which will apply behaviors to role players before execution and remove the behaviors after execution.

Alternatively you may define your own methods then declare them as triggers afterward.

Example:

trigger :some_event do
  # code here
end

def some_event
  # code here
end
trigger :some_event


31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/surrounded/context/trigger_controls.rb', line 31

def trigger(*names, &block)
  if block.nil?
    names.each do |name|
      convert_method_to_trigger(name)
    end
  else
    name = names.first
    define_trigger_action(*names, &block)
    define_trigger(name)
    store_trigger(name)
  end
end

#trigger_action_moduleObject



81
82
83
# File 'lib/surrounded/context/trigger_controls.rb', line 81

def trigger_action_module
  const_get(:TriggerMethods, false)
end

#trigger_return_content(name) ⇒ Object



69
70
71
72
73
74
75
# File 'lib/surrounded/context/trigger_controls.rb', line 69

def trigger_return_content(name)
  if method_defined?(name)
    %(super)
  else
    %{self.send("__trigger_#{name}", ...)}
  end
end

#triggersObject

Provides a Set of all available trigger methods where behaviors will be applied to the roles before execution and removed afterward.



7
8
9
# File 'lib/surrounded/context/trigger_controls.rb', line 7

def triggers
  @triggers.dup
end