code refactor to remove repetition

Umar M. Sheikh 11 years ago
parent
commit
ca60b7d409
1 changed files with 6 additions and 19 deletions
  1. 6 19
      app/models/agents/code_agent.rb

+ 6 - 19
app/models/agents/code_agent.rb

@@ -56,37 +56,24 @@ module Agents
56 56
       true
57 57
     end
58 58
 
59
-    def execute_js
59
+    def execute_js(incoming_events)
60 60
       context = V8::Context.new
61 61
       context.eval(example_js)
62
-      context.eval(options['code']) # should override the run function.
63 62
       context["create_event"] = lambda {|x,y| puts x; puts y; create_event payload: JSON.parse(y)}
64
-      a, m, e, o = [self.attributes.to_json, self.memory.to_json, self.events.to_json, self.options.to_json]
63
+      context.eval(options['code']) # should override the run function.
64
+      a, m, e, o = [self.attributes.to_json, self.memory.to_json, incoming_events.to_json, self.options.to_json]
65 65
       string = "a = new Agent('#{m}','#{e}','#{o}','#{a}');"
66 66
       context.eval(string)
67 67
       context.eval("a.run();")
68 68
     end
69 69
     def check
70
-      context = V8::Context.new
71
-      context.eval(example_js)
72
-      context["create_event"] = lambda {|x,y| puts x; puts y; create_event payload: JSON.parse(y)}
73
-      context.eval(options['code']) # should override the run function.
74
-      a, m, e, o = [self.attributes.to_json, self.memory.to_json, "".to_json, self.options.to_json]
75
-      string = "a = new Agent('#{m}','#{e}','#{o}','#{a}');"
76
-      context.eval(string)
77
-      context.eval("a.run();")
70
+      execute_js("")
78 71
     end
79 72
 
80 73
     def receive(incoming_events)
81
-      context = V8::Context.new
82
-      context.eval(example_js)
83
-      context.eval(options['code']) # should override the run function.
84
-      context["create_event"] = lambda {|x,y| puts x; puts y; create_event payload: JSON.parse(y)}
85
-      a, m, e, o = [self.attributes.to_json, self.memory.to_json, incoming_events.to_json, self.options.to_json]
86
-      string = "a = new Agent('#{m}','#{e}','#{o}','#{a}');"
87
-      context.eval(string)
88
-      context.eval("a.run();")
74
+      execute_js(incoming_events)
89 75
     end
76
+
90 77
     def default_options
91 78
     js_code = "Agent.prototype.run = function(){ var pd = JSON.stringify({memory: this.memory, events: this.events, options: this.options});create_event(pd); }"
92 79
     {