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



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

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



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

def define_trigger(name)
  line = __LINE__
  self.class_eval %{
    def #{name}(*args, &block)
      begin
        apply_behaviors

        #{trigger_return_content(name)}

      ensure
        remove_behaviors
      end
    end
  }, __FILE__, line
end

#define_trigger_action(*name_and_args, &block) ⇒ Object



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

def define_trigger_action(*name_and_args, &block)
  trigger_action_module.module_eval do
    define_method(*name_and_args, &block)
  end
end

#store_trigger(*names) ⇒ Object



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

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


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

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, &block)
    store_trigger(name)
  end
end

#trigger_action_moduleObject



86
87
88
# File 'lib/surrounded/context/trigger_controls.rb', line 86

def trigger_action_module
  self.const_get('TriggerMethods', false)
end

#trigger_return_content(name) ⇒ Object



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

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

#triggersObject

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



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

def triggers
  @triggers.dup
end