Merge pull request #382 from cantino/interpolated_options

Add memoized interpolated_options and used it everywhere.

Andrew Cantino 10 years ago
parent
commit
fb0b423a83
50 changed files with 250 additions and 272 deletions
  1. 0 3
      app/concerns/email_concern.rb
  2. 17 13
      app/concerns/liquid_interpolatable.rb
  3. 1 0
      app/models/agent.rb
  4. 4 4
      app/models/agents/adioso_agent.rb
  5. 2 2
      app/models/agents/basecamp_agent.rb
  6. 7 8
      app/models/agents/data_output_agent.rb
  7. 1 1
      app/models/agents/email_agent.rb
  8. 1 1
      app/models/agents/email_digest_agent.rb
  9. 6 6
      app/models/agents/event_formatting_agent.rb
  10. 4 4
      app/models/agents/ftpsite_agent.rb
  11. 6 6
      app/models/agents/growl_agent.rb
  12. 2 4
      app/models/agents/hipchat_agent.rb
  13. 6 8
      app/models/agents/human_task_agent.rb
  14. 7 7
      app/models/agents/imap_folder_agent.rb
  15. 7 9
      app/models/agents/jabber_agent.rb
  16. 7 7
      app/models/agents/java_script_agent.rb
  17. 8 8
      app/models/agents/jira_agent.rb
  18. 11 11
      app/models/agents/mqtt_agent.rb
  19. 11 13
      app/models/agents/peak_detector_agent.rb
  20. 6 6
      app/models/agents/post_agent.rb
  21. 4 4
      app/models/agents/public_transport_agent.rb
  22. 3 4
      app/models/agents/pushbullet_agent.rb
  23. 24 23
      app/models/agents/pushover_agent.rb
  24. 2 2
      app/models/agents/sentiment_agent.rb
  25. 8 7
      app/models/agents/shell_command_agent.rb
  26. 4 5
      app/models/agents/slack_agent.rb
  27. 1 1
      app/models/agents/stubhub_agent.rb
  28. 6 8
      app/models/agents/translation_agent.rb
  29. 9 8
      app/models/agents/trigger_agent.rb
  30. 9 9
      app/models/agents/twilio_agent.rb
  31. 2 3
      app/models/agents/twitter_publish_agent.rb
  32. 5 5
      app/models/agents/twitter_stream_agent.rb
  33. 5 5
      app/models/agents/twitter_user_agent.rb
  34. 7 7
      app/models/agents/weather_agent.rb
  35. 4 4
      app/models/agents/webhook_agent.rb
  36. 22 22
      app/models/agents/website_agent.rb
  37. 3 3
      app/models/agents/weibo_publish_agent.rb
  38. 3 3
      app/models/agents/weibo_user_agent.rb
  39. 9 6
      spec/models/agent_spec.rb
  40. 0 2
      spec/models/agents/data_output_agent_spec.rb
  41. 0 2
      spec/models/agents/hipchat_agent_spec.rb
  42. 0 2
      spec/models/agents/human_task_agent_spec.rb
  43. 0 2
      spec/models/agents/jabber_agent_spec.rb
  44. 0 2
      spec/models/agents/peak_detector_agent_spec.rb
  45. 0 2
      spec/models/agents/pushbullet_agent_spec.rb
  46. 4 3
      spec/models/agents/shell_command_agent_spec.rb
  47. 0 2
      spec/models/agents/slack_agent_spec.rb
  48. 0 2
      spec/models/agents/translation_agent_spec.rb
  49. 0 2
      spec/models/agents/trigger_agent_spec.rb
  50. 2 1
      spec/support/shared_examples/liquid_interpolatable.rb

+ 0 - 3
app/concerns/email_concern.rb

@@ -31,7 +31,4 @@ module EmailConcern
31 31
   def present_hash(hash, skip_key = nil)
32 32
     hash.to_a.sort_by {|a| a.first.to_s }.map { |k, v| "#{k}: #{v}" unless k.to_s == skip_key.to_s }.compact
33 33
   end
34
-
35
-  module ClassMethods
36
-  end
37 34
 end

+ 17 - 13
app/concerns/liquid_interpolatable.rb

@@ -1,22 +1,26 @@
1 1
 module LiquidInterpolatable
2 2
   extend ActiveSupport::Concern
3 3
 
4
-  def interpolate_options(options, payload)
5
-    case options.class.to_s
6
-    when 'String'
7
-      interpolate_string(options, payload)
8
-    when 'ActiveSupport::HashWithIndifferentAccess', 'Hash'
9
-      duped_options = options.dup
10
-      duped_options.each do |key, value|
11
-        duped_options[key] = interpolate_options(value, payload)
12
-      end
13
-    when 'Array'
14
-      options.collect do |value|
15
-        interpolate_options(value, payload)
16
-      end
4
+  def interpolate_options(options, payload = {})
5
+    case options
6
+      when String
7
+        interpolate_string(options, payload)
8
+      when ActiveSupport::HashWithIndifferentAccess, Hash
9
+        options.inject(ActiveSupport::HashWithIndifferentAccess.new) { |memo, (key, value)| memo[key] = interpolate_options(value, payload); memo }
10
+      when Array
11
+        options.map { |value| interpolate_options(value, payload) }
12
+      else
13
+        options
17 14
     end
18 15
   end
19 16
 
17
+  def interpolated(payload = {})
18
+    key = [options, payload]
19
+    @interpolated_cache ||= {}
20
+    @interpolated_cache[key] ||= interpolate_options(options, payload)
21
+    @interpolated_cache[key]
22
+  end
23
+
20 24
   def interpolate_string(string, payload)
21 25
     Liquid::Template.parse(string).render!(payload, registers: {agent: self})
22 26
   end

+ 1 - 0
app/models/agent.rb

@@ -12,6 +12,7 @@ class Agent < ActiveRecord::Base
12 12
   include JSONSerializedField
13 13
   include RDBMSFunctions
14 14
   include WorkingHelpers
15
+  include LiquidInterpolatable
15 16
   include HasGuid
16 17
 
17 18
   markdown_class_attributes :description, :event_description

+ 4 - 4
app/models/agents/adioso_agent.rb

@@ -54,9 +54,9 @@ module Agents
54 54
     end
55 55
 
56 56
     def check
57
-      auth_options = {:basic_auth => {:username =>options[:username], :password=>options['password']}}
58
-      parse_response = HTTParty.get "http://api.adioso.com/v2/search/parse?q=#{URI.encode(options['from'])}+to+#{URI.encode(options['to'])}", auth_options
59
-      fare_request = parse_response["search_url"].gsub /(end=)(\d*)([^\d]*)(\d*)/, "\\1#{date_to_unix_epoch(options['end_date'])}\\3#{date_to_unix_epoch(options['start_date'])}"
57
+      auth_options = {:basic_auth => {:username =>interpolated[:username], :password=>interpolated['password']}}
58
+      parse_response = HTTParty.get "http://api.adioso.com/v2/search/parse?q=#{URI.encode(interpolated['from'])}+to+#{URI.encode(interpolated['to'])}", auth_options
59
+      fare_request = parse_response["search_url"].gsub /(end=)(\d*)([^\d]*)(\d*)/, "\\1#{date_to_unix_epoch(interpolated['end_date'])}\\3#{date_to_unix_epoch(interpolated['start_date'])}"
60 60
       fare = HTTParty.get fare_request, auth_options
61 61
 
62 62
 			if fare["warnings"]
@@ -64,7 +64,7 @@ module Agents
64 64
 			else
65 65
 				event = fare["results"].min {|a,b| a["cost"] <=> b["cost"]}
66 66
 				event["date"]  = Time.at(event["date"]).to_date.httpdate[0..15]
67
-				event["route"] = "#{options['from']} to #{options['to']}"
67
+				event["route"] = "#{interpolated['from']} to #{interpolated['to']}"
68 68
 				create_event :payload => event
69 69
 			end
70 70
     end

+ 2 - 2
app/models/agents/basecamp_agent.rb

@@ -76,11 +76,11 @@ module Agents
76 76
 
77 77
   private
78 78
     def request_url
79
-      "https://basecamp.com/#{URI.encode(options[:user_id].to_s)}/api/v1/projects/#{URI.encode(options[:project_id].to_s)}/events.json"
79
+      "https://basecamp.com/#{URI.encode(interpolated[:user_id].to_s)}/api/v1/projects/#{URI.encode(interpolated[:project_id].to_s)}/events.json"
80 80
     end
81 81
 
82 82
     def request_options
83
-      {:basic_auth => {:username =>options[:username], :password=>options[:password]}, :headers => {"User-Agent" => "Huginn (https://github.com/cantino/huginn)"}}
83
+      {:basic_auth => {:username => interpolated[:username], :password => interpolated[:password]}, :headers => {"User-Agent" => "Huginn (https://github.com/cantino/huginn)"}}
84 84
     end
85 85
 
86 86
     def query_parameters

+ 7 - 8
app/models/agents/data_output_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class DataOutputAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
 
7 5
     description  do
@@ -52,6 +50,7 @@ module Agents
52 50
       unless options['secrets'].is_a?(Array) && options['secrets'].length > 0
53 51
         errors.add(:base, "Please specify one or more secrets for 'authenticating' incoming feed requests")
54 52
       end
53
+
55 54
       unless options['expected_receive_period_in_days'].present? && options['expected_receive_period_in_days'].to_i > 0
56 55
         errors.add(:base, "Please provide 'expected_receive_period_in_days' to indicate how many days can pass before this Agent is considered to be not working")
57 56
       end
@@ -62,27 +61,27 @@ module Agents
62 61
     end
63 62
 
64 63
     def events_to_show
65
-      (options['events_to_show'].presence || 40).to_i
64
+      (interpolated['events_to_show'].presence || 40).to_i
66 65
     end
67 66
 
68 67
     def feed_ttl
69
-      (options['ttl'].presence || 60).to_i
68
+      (interpolated['ttl'].presence || 60).to_i
70 69
     end
71 70
 
72 71
     def feed_title
73
-      options['template']['title'].presence || "#{name} Event Feed"
72
+      interpolated['template']['title'].presence || "#{name} Event Feed"
74 73
     end
75 74
 
76 75
     def feed_link
77
-      options['template']['link'].presence || "https://#{ENV['DOMAIN']}"
76
+      interpolated['template']['link'].presence || "https://#{ENV['DOMAIN']}"
78 77
     end
79 78
 
80 79
     def feed_description
81
-      options['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
80
+      interpolated['template']['description'].presence || "A feed of Events received by the '#{name}' Huginn Agent"
82 81
     end
83 82
 
84 83
     def receive_web_request(params, method, format)
85
-      if options['secrets'].include?(params['secret'])
84
+      if interpolated['secrets'].include?(params['secret'])
86 85
         items = received_events.order('id desc').limit(events_to_show).map do |event|
87 86
           interpolated = interpolate_options(options['template']['item'], event.payload)
88 87
           interpolated['guid'] = event.id

+ 1 - 1
app/models/agents/email_agent.rb

@@ -25,7 +25,7 @@ module Agents
25 25
     def receive(incoming_events)
26 26
       incoming_events.each do |event|
27 27
         log "Sending digest mail to #{user.email} with event #{event.id}"
28
-        SystemMailer.delay.send_message(:to => user.email, :subject => options['subject'], :headline => options['headline'], :groups => [present(event.payload)])
28
+        SystemMailer.delay.send_message(:to => user.email, :subject => interpolated(event.payload)['subject'], :headline => interpolated(event.payload)['headline'], :groups => [present(event.payload)])
29 29
       end
30 30
     end
31 31
   end

+ 1 - 1
app/models/agents/email_digest_agent.rb

@@ -37,7 +37,7 @@ module Agents
37 37
         ids = self.memory['events'].join(",")
38 38
         groups = self.memory['queue'].map { |payload| present(payload) }
39 39
         log "Sending digest mail to #{user.email} with events [#{ids}]"
40
-        SystemMailer.delay.send_message(:to => user.email, :subject => options['subject'], :headline => options['headline'], :groups => groups)
40
+        SystemMailer.delay.send_message(:to => user.email, :subject => interpolated['subject'], :headline => interpolated['headline'], :groups => groups)
41 41
         self.memory['queue'] = []
42 42
         self.memory['events'] = []
43 43
       end

+ 6 - 6
app/models/agents/event_formatting_agent.rb

@@ -1,6 +1,5 @@
1 1
 module Agents
2 2
   class EventFormattingAgent < Agent
3
-    include LiquidInterpolatable
4 3
     cannot_be_scheduled!
5 4
 
6 5
     description <<-MD
@@ -81,7 +80,7 @@ module Agents
81 80
     after_save :clear_matchers
82 81
 
83 82
     def validate_options
84
-      errors.add(:base, "instructions, mode, skip_agent, and skip_created_at all need to be present.") unless options['instructions'].present? and options['mode'].present? and options['skip_agent'].present? and options['skip_created_at'].present?
83
+      errors.add(:base, "instructions, mode, skip_agent, and skip_created_at all need to be present.") unless options['instructions'].present? && options['mode'].present? && options['skip_agent'].present? && options['skip_created_at'].present?
85 84
 
86 85
       validate_matchers
87 86
     end
@@ -105,11 +104,12 @@ module Agents
105 104
 
106 105
     def receive(incoming_events)
107 106
       incoming_events.each do |event|
108
-        formatted_event = options['mode'].to_s == "merge" ? event.payload.dup : {}
109 107
         payload = perform_matching(event.payload)
110
-        formatted_event.merge! interpolate_options(options['instructions'], payload)
111
-        formatted_event['agent'] = Agent.find(event.agent_id).type.slice!(8..-1) unless options['skip_agent'].to_s == "true"
112
-        formatted_event['created_at'] = event.created_at unless options['skip_created_at'].to_s == "true"
108
+        opts = interpolated(payload)
109
+        formatted_event = opts['mode'].to_s == "merge" ? event.payload.dup : {}
110
+        formatted_event.merge! opts['instructions']
111
+        formatted_event['agent'] = Agent.find(event.agent_id).type.slice!(8..-1) unless opts['skip_agent'].to_s == "true"
112
+        formatted_event['created_at'] = event.created_at unless opts['skip_created_at'].to_s == "true"
113 113
         create_event :payload => formatted_event
114 114
       end
115 115
     end

+ 4 - 4
app/models/agents/ftpsite_agent.rb

@@ -29,7 +29,7 @@ module Agents
29 29
     MD
30 30
 
31 31
     def working?
32
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
32
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
33 33
     end
34 34
 
35 35
     def default_options
@@ -90,10 +90,10 @@ module Agents
90 90
     end
91 91
 
92 92
     def each_entry
93
-      patterns = options['patterns']
93
+      patterns = interpolated['patterns']
94 94
 
95 95
       after =
96
-        if str = options['after']
96
+        if str = interpolated['after']
97 97
           Time.parse(str)
98 98
         else
99 99
           Time.at(0)
@@ -174,7 +174,7 @@ module Agents
174 174
     end
175 175
 
176 176
     def base_uri
177
-      @base_uri ||= URI(options['url'])
177
+      @base_uri ||= URI(interpolated['url'])
178 178
     end
179 179
 
180 180
     def saving_entries

+ 6 - 6
app/models/agents/growl_agent.rb

@@ -26,7 +26,7 @@ module Agents
26 26
     end
27 27
     
28 28
     def working?
29
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
29
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
30 30
     end
31 31
 
32 32
     def validate_options
@@ -36,13 +36,13 @@ module Agents
36 36
     end
37 37
     
38 38
     def register_growl
39
-      @growler = Growl.new options['growl_server'], options['growl_app_name'], "GNTP"
40
-      @growler.password = options['growl_password']
41
-      @growler.add_notification options['growl_notification_name']
39
+      @growler = Growl.new interpolated['growl_server'], interpolated['growl_app_name'], "GNTP"
40
+      @growler.password = interpolated['growl_password']
41
+      @growler.add_notification interpolated['growl_notification_name']
42 42
     end
43 43
     
44 44
     def notify_growl(subject, message)
45
-      @growler.notify(options['growl_notification_name'],subject,message)
45
+      @growler.notify(interpolated['growl_notification_name'], subject, message)
46 46
     end
47 47
 
48 48
     def receive(incoming_events)
@@ -51,7 +51,7 @@ module Agents
51 51
         message = (event.payload['message'] || event.payload['text']).to_s
52 52
         subject = event.payload['subject'].to_s
53 53
         if message.present? && subject.present?
54
-          log "Sending Growl notification '#{subject}': '#{message}' to #{options['growl_server']} with event #{event.id}"
54
+          log "Sending Growl notification '#{subject}': '#{message}' to #{interpolated(event.payload)['growl_server']} with event #{event.id}"
55 55
           notify_growl(subject,message)
56 56
         else
57 57
           log "Event #{event.id} not sent, message and subject expected"

+ 2 - 4
app/models/agents/hipchat_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class HipchatAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
     cannot_create_events!
7 5
 
@@ -42,9 +40,9 @@ module Agents
42 40
     end
43 41
 
44 42
     def receive(incoming_events)
45
-      client = HipChat::Client.new(options[:auth_token])
43
+      client = HipChat::Client.new(interpolated[:auth_token])
46 44
       incoming_events.each do |event|
47
-        mo = interpolate_options options, event.payload
45
+        mo = interpolated(event.payload)
48 46
         client[mo[:room_name]].send(mo[:username], mo[:message], :notify => mo[:notify].to_s == 'true' ? 1 : 0, :color => mo[:color])
49 47
       end
50 48
     end

+ 6 - 8
app/models/agents/human_task_agent.rb

@@ -2,8 +2,6 @@ require 'rturk'
2 2
 
3 3
 module Agents
4 4
   class HumanTaskAgent < Agent
5
-    include LiquidInterpolatable
6
-
7 5
     default_schedule "every_10m"
8 6
 
9 7
     description <<-MD
@@ -204,20 +202,20 @@ module Agents
204 202
     end
205 203
 
206 204
     def working?
207
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
205
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
208 206
     end
209 207
 
210 208
     def check
211 209
       review_hits
212 210
 
213
-      if options['trigger_on'] == "schedule" && (memory['last_schedule'] || 0) <= Time.now.to_i - options['submission_period'].to_i * 60 * 60
211
+      if interpolated['trigger_on'] == "schedule" && (memory['last_schedule'] || 0) <= Time.now.to_i - interpolated['submission_period'].to_i * 60 * 60
214 212
         memory['last_schedule'] = Time.now.to_i
215 213
         create_basic_hit
216 214
       end
217 215
     end
218 216
 
219 217
     def receive(incoming_events)
220
-      if options['trigger_on'] == "event"
218
+      if interpolated['trigger_on'] == "event"
221 219
         incoming_events.each do |event|
222 220
           create_basic_hit event
223 221
         end
@@ -227,11 +225,11 @@ module Agents
227 225
     protected
228 226
 
229 227
     def take_majority?
230
-      options['combination_mode'] == "take_majority" || options['take_majority'] == "true"
228
+      interpolated['combination_mode'] == "take_majority" || interpolated['take_majority'] == "true"
231 229
     end
232 230
 
233 231
     def create_poll?
234
-      options['combination_mode'] == "poll"
232
+      interpolated['combination_mode'] == "poll"
235 233
     end
236 234
 
237 235
     def event_for_hit(hit_id)
@@ -367,7 +365,7 @@ module Agents
367 365
     end
368 366
 
369 367
     def all_questions_are_numeric?
370
-      options['hit']['questions'].all? do |question|
368
+      interpolated['hit']['questions'].all? do |question|
371 369
         question['selections'].all? do |selection|
372 370
           selection['key'] == selection['key'].to_f.to_s || selection['key'] == selection['key'].to_i.to_s
373 371
         end

+ 7 - 7
app/models/agents/imap_folder_agent.rb

@@ -111,7 +111,7 @@ module Agents
111 111
     }
112 112
 
113 113
     def working?
114
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
114
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
115 115
     end
116 116
 
117 117
     def default_options
@@ -240,7 +240,7 @@ module Agents
240 240
         matched_part = nil
241 241
         matches = {}
242 242
 
243
-        options['conditions'].all? { |key, value|
243
+        interpolated['conditions'].all? { |key, value|
244 244
           case key
245 245
           when 'subject'
246 246
             value.present? or next true
@@ -308,7 +308,7 @@ module Agents
308 308
           notified << mail.message_id if mail.message_id
309 309
         end
310 310
 
311
-        if options['mark_as_read']
311
+        if interpolated['mark_as_read']
312 312
           log 'Marking as read'
313 313
           mail.mark_as_read
314 314
         end
@@ -322,14 +322,14 @@ module Agents
322 322
     end
323 323
 
324 324
     def each_unread_mail
325
-      host, port, ssl, username = options.values_at(:host, :port, :ssl, :username)
325
+      host, port, ssl, username = interpolated.values_at(:host, :port, :ssl, :username)
326 326
 
327 327
       log "Connecting to #{host}#{':%d' % port if port}#{' via SSL' if ssl}"
328 328
       Client.open(host, Integer(port), ssl) { |imap|
329 329
         log "Logging in as #{username}"
330
-        imap.login(username, options[:password])
330
+        imap.login(username, interpolated[:password])
331 331
 
332
-        options['folders'].each { |folder|
332
+        interpolated['folders'].each { |folder|
333 333
           log "Selecting the folder: %s" % folder
334 334
 
335 335
           imap.select(folder)
@@ -351,7 +351,7 @@ module Agents
351 351
     end
352 352
 
353 353
     def mime_types
354
-      options['mime_types'] || %w[text/plain text/enriched text/html]
354
+      interpolated['mime_types'] || %w[text/plain text/enriched text/html]
355 355
     end
356 356
 
357 357
     private

+ 7 - 9
app/models/agents/jabber_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class JabberAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
     cannot_create_events!
7 5
 
@@ -30,12 +28,12 @@ module Agents
30 28
     end
31 29
 
32 30
     def working?
33
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
31
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
34 32
     end
35 33
 
36 34
     def receive(incoming_events)
37 35
       incoming_events.each do |event|
38
-        log "Sending IM to #{options['jabber_receiver']} with event #{event.id}"
36
+        log "Sending IM to #{interpolated['jabber_receiver']} with event #{event.id}"
39 37
         deliver body(event)
40 38
       end
41 39
     end
@@ -45,15 +43,15 @@ module Agents
45 43
     end
46 44
 
47 45
     def deliver(text)
48
-      client.send Jabber::Message::new(options['jabber_receiver'], text).set_type(:chat)
46
+      client.send Jabber::Message::new(interpolated['jabber_receiver'], text).set_type(:chat)
49 47
     end
50 48
 
51 49
     private
52 50
 
53 51
     def client
54
-      Jabber::Client.new(Jabber::JID::new(options['jabber_sender'])).tap do |sender|
55
-        sender.connect(options['jabber_server'], (options['jabber_port'] || '5222'))
56
-        sender.auth(options['jabber_password'])
52
+      Jabber::Client.new(Jabber::JID::new(interpolated['jabber_sender'])).tap do |sender|
53
+        sender.connect(interpolated['jabber_server'], interpolated['jabber_port'] || '5222')
54
+        sender.auth interpolated['jabber_password']
57 55
       end
58 56
     end
59 57
 
@@ -62,7 +60,7 @@ module Agents
62 60
     end
63 61
 
64 62
     def body(event)
65
-      interpolate_string(options['message'], event.payload)
63
+      interpolated(event.payload)['message']
66 64
     end
67 65
   end
68 66
 end

+ 7 - 7
app/models/agents/java_script_agent.rb

@@ -35,12 +35,12 @@ module Agents
35 35
     def working?
36 36
       return false if recent_error_logs?
37 37
 
38
-      if options['expected_update_period_in_days'].present?
39
-        return false unless event_created_within?(options['expected_update_period_in_days'])
38
+      if interpolated['expected_update_period_in_days'].present?
39
+        return false unless event_created_within?(interpolated['expected_update_period_in_days'])
40 40
       end
41 41
 
42
-      if options['expected_receive_period_in_days'].present?
43
-        return false unless last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago
42
+      if interpolated['expected_receive_period_in_days'].present?
43
+        return false unless last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago
44 44
       end
45 45
 
46 46
       true
@@ -92,7 +92,7 @@ module Agents
92 92
 
93 93
       context["doCreateEvent"] = lambda { |a, y| create_event(payload: clean_nans(JSON.parse(y))).payload.to_json }
94 94
       context["getIncomingEvents"] = lambda { |a| incoming_events.to_json }
95
-      context["getOptions"] = lambda { |a, x| options.to_json }
95
+      context["getOptions"] = lambda { |a, x| interpolated.to_json }
96 96
       context["doLog"] = lambda { |a, x| log x }
97 97
       context["doError"] = lambda { |a, x| error x }
98 98
       context["getMemory"] = lambda do |a, x, y|
@@ -112,12 +112,12 @@ module Agents
112 112
       if cred
113 113
         credential(cred) || 'Agent.check = function() { this.error("Unable to find credential"); };'
114 114
       else
115
-        options['code']
115
+        interpolated['code']
116 116
       end
117 117
     end
118 118
 
119 119
     def credential_referenced_by_code
120
-      options['code'] =~ /\Acredential:(.*)\Z/ && $1
120
+      interpolated['code'] =~ /\Acredential:(.*)\Z/ && $1
121 121
     end
122 122
 
123 123
     def setup_javascript

+ 8 - 8
app/models/agents/jira_agent.rb

@@ -56,7 +56,7 @@ module Agents
56 56
     end
57 57
 
58 58
     def working?
59
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
59
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
60 60
     end
61 61
 
62 62
     def check
@@ -81,14 +81,14 @@ module Agents
81 81
 
82 82
   private
83 83
     def request_url(jql, start_at)
84
-      "#{options[:jira_url]}/rest/api/2/search?jql=#{CGI::escape(jql)}&fields=*all&startAt=#{start_at}"
84
+      "#{interpolated[:jira_url]}/rest/api/2/search?jql=#{CGI::escape(jql)}&fields=*all&startAt=#{start_at}"
85 85
     end
86 86
 
87 87
     def request_options
88 88
       ropts = {:headers => {"User-Agent" => "Huginn (https://github.com/cantino/huginn)"}}
89 89
 
90
-      if !options[:username].empty?
91
-        ropts = ropts.merge({:basic_auth => {:username =>options[:username], :password=>options[:password]}})
90
+      if !interpolated[:username].empty?
91
+        ropts = ropts.merge({:basic_auth => {:username =>interpolated[:username], :password=>interpolated[:password]}})
92 92
       end
93 93
 
94 94
       ropts
@@ -121,10 +121,10 @@ module Agents
121 121
 
122 122
       jql = ""
123 123
 
124
-      if !options[:jql].empty? && since
125
-        jql = "(#{options[:jql]}) and updated >= '#{since.strftime('%Y-%m-%d %H:%M')}'"
124
+      if !interpolated[:jql].empty? && since
125
+        jql = "(#{interpolated[:jql]}) and updated >= '#{since.strftime('%Y-%m-%d %H:%M')}'"
126 126
       else
127
-        jql = options[:jql] if !options[:jql].empty?
127
+        jql = interpolated[:jql] if !interpolated[:jql].empty?
128 128
         jql = "updated >= '#{since.strftime('%Y-%m-%d %H:%M')}'" if since
129 129
       end
130 130
 
@@ -142,7 +142,7 @@ module Agents
142 142
           raise RuntimeError.new("There is no progress while fetching issues")
143 143
         end
144 144
 
145
-        if Time.now > start_time + options['timeout'].to_i * 60
145
+        if Time.now > start_time + interpolated['timeout'].to_i * 60
146 146
           raise RuntimeError.new("Timeout exceeded while fetching issues")
147 147
         end
148 148
 

+ 11 - 11
app/models/agents/mqtt_agent.rb

@@ -68,13 +68,13 @@ module Agents
68 68
 
69 69
     def validate_options
70 70
       unless options['uri'].present? &&
71
-        options['topic'].present?
71
+             options['topic'].present?
72 72
         errors.add(:base, "topic and uri are required")
73 73
       end
74 74
     end
75 75
 
76 76
     def working?
77
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
77
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
78 78
     end
79 79
 
80 80
     def default_options
@@ -91,13 +91,13 @@ module Agents
91 91
     end
92 92
 
93 93
     def mqtt_client
94
-      @client ||= MQTT::Client.new(options['uri'])
94
+      @client ||= MQTT::Client.new(interpolated['uri'])
95 95
 
96
-      if options['ssl']
97
-        @client.ssl = options['ssl'].to_sym
98
-        @client.ca_file = options['ca_file']
99
-        @client.cert_file = options['cert_file']
100
-        @client.key_file = options['key_file']
96
+      if interpolated['ssl']
97
+        @client.ssl = interpolated['ssl'].to_sym
98
+        @client.ca_file = interpolated['ca_file']
99
+        @client.cert_file = interpolated['cert_file']
100
+        @client.key_file = interpolated['key_file']
101 101
       end
102 102
 
103 103
       @client
@@ -106,7 +106,7 @@ module Agents
106 106
     def receive(incoming_events)
107 107
       mqtt_client.connect do |c|
108 108
         incoming_events.each do |event|
109
-          c.publish(options['topic'], payload)
109
+          c.publish(interpolated(event.payload)['topic'], event.payload)
110 110
         end
111 111
 
112 112
         c.disconnect
@@ -117,8 +117,8 @@ module Agents
117 117
     def check
118 118
       mqtt_client.connect do |c|
119 119
 
120
-        Timeout::timeout((options['max_read_time'].presence || 15).to_i) {
121
-          c.get(options['topic']) do |topic, message|
120
+        Timeout::timeout((interpolated['max_read_time'].presence || 15).to_i) {
121
+          c.get(interpolated['topic']) do |topic, message|
122 122
 
123 123
             # A lot of services generate JSON. Try that first
124 124
             payload = JSON.parse(message) rescue message

+ 11 - 13
app/models/agents/peak_detector_agent.rb

@@ -2,8 +2,6 @@ require 'pp'
2 2
 
3 3
 module Agents
4 4
   class PeakDetectorAgent < Agent
5
-    include LiquidInterpolatable
6
-
7 5
     cannot_be_scheduled!
8 6
 
9 7
     description <<-MD
@@ -45,7 +43,7 @@ module Agents
45 43
     end
46 44
 
47 45
     def working?
48
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
46
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
49 47
     end
50 48
 
51 49
     def receive(incoming_events)
@@ -69,7 +67,7 @@ module Agents
69 67
         if newest_value > average_value + std_multiple * standard_deviation
70 68
           memory['peaks'][group] << newest_time
71 69
           memory['peaks'][group].reject! { |p| p <= newest_time - window_duration }
72
-          create_event :payload => { 'message' => interpolate_string(options['message'], event.payload), 'peak' => newest_value, 'peak_time' => newest_time, 'grouped_by' => group.to_s }
70
+          create_event :payload => { 'message' => interpolated(event.payload)['message'], 'peak' => newest_value, 'peak_time' => newest_time, 'grouped_by' => group.to_s }
73 71
         end
74 72
       end
75 73
     end
@@ -94,33 +92,33 @@ module Agents
94 92
     end
95 93
 
96 94
     def window_duration
97
-      if options['window_duration'].present? # The older option
98
-        options['window_duration'].to_i
95
+      if interpolated['window_duration'].present? # The older option
96
+        interpolated['window_duration'].to_i
99 97
       else
100
-        (options['window_duration_in_days'] || 14).to_f.days
98
+        (interpolated['window_duration_in_days'] || 14).to_f.days
101 99
       end
102 100
     end
103 101
 
104 102
     def std_multiple
105
-      (options['std_multiple'] || 3).to_f
103
+      (interpolated['std_multiple'] || 3).to_f
106 104
     end
107 105
 
108 106
     def peak_spacing
109
-      if options['peak_spacing'].present? # The older option
110
-        options['peak_spacing'].to_i
107
+      if interpolated['peak_spacing'].present? # The older option
108
+        interpolated['peak_spacing'].to_i
111 109
       else
112
-        (options['min_peak_spacing_in_days'] || 2).to_f.days
110
+        (interpolated['min_peak_spacing_in_days'] || 2).to_f.days
113 111
       end
114 112
     end
115 113
 
116 114
     def group_for(event)
117
-      ((options['group_by_path'].present? && Utils.value_at(event.payload, options['group_by_path'])) || 'no_group')
115
+      ((interpolated['group_by_path'].present? && Utils.value_at(event.payload, interpolated['group_by_path'])) || 'no_group')
118 116
     end
119 117
 
120 118
     def remember(group, event)
121 119
       memory['data'] ||= {}
122 120
       memory['data'][group] ||= []
123
-      memory['data'][group] << [ Utils.value_at(event.payload, options['value_path']), event.created_at.to_i ]
121
+      memory['data'][group] << [ Utils.value_at(event.payload, interpolated['value_path']), event.created_at.to_i ]
124 122
       cleanup group
125 123
     end
126 124
 

+ 6 - 6
app/models/agents/post_agent.rb

@@ -27,15 +27,15 @@ module Agents
27 27
     end
28 28
 
29 29
     def working?
30
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
30
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
31 31
     end
32 32
 
33 33
     def method
34
-      (options['method'].presence || 'post').to_s.downcase
34
+      (interpolated['method'].presence || 'post').to_s.downcase
35 35
     end
36 36
 
37 37
     def headers
38
-      options['headers'].presence || {}
38
+      interpolated['headers'].presence || {}
39 39
     end
40 40
 
41 41
     def validate_options
@@ -58,16 +58,16 @@ module Agents
58 58
 
59 59
     def receive(incoming_events)
60 60
       incoming_events.each do |event|
61
-        handle (options['payload'].presence || {}).merge(event.payload)
61
+        handle (interpolated(event.payload)['payload'].presence || {}).merge(event.payload)
62 62
       end
63 63
     end
64 64
 
65 65
     def check
66
-      handle options['payload'].presence || {}
66
+      handle interpolated['payload'].presence || {}
67 67
     end
68 68
 
69 69
     def generate_uri(params = nil)
70
-      uri = URI options[:post_url]
70
+      uri = URI interpolated[:post_url]
71 71
       uri.query = URI.encode_www_form(Hash[URI.decode_www_form(uri.query || '')].merge(params)) if params
72 72
       uri
73 73
     end

+ 4 - 4
app/models/agents/public_transport_agent.rb

@@ -48,12 +48,12 @@ module Agents
48 48
     MD
49 49
 
50 50
     def check_url
51
-      stop_query = URI.encode(options["stops"].collect{|a| "&stops=#{a}"}.join)
52
-      "http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=#{options["agency"]}#{stop_query}"
51
+      stop_query = URI.encode(interpolated["stops"].collect{|a| "&stops=#{a}"}.join)
52
+      "http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=#{interpolated["agency"]}#{stop_query}"
53 53
     end
54 54
 
55 55
     def stops
56
-      options["stops"].collect{|a| a.split("|").last}
56
+      interpolated["stops"].collect{|a| a.split("|").last}
57 57
     end
58 58
 
59 59
     def check
@@ -65,7 +65,7 @@ module Agents
65 65
         predictions.each do |pr|
66 66
           parent = pr.parent.parent
67 67
           vals = {"routeTitle" => parent["routeTitle"], "stopTag" => parent["stopTag"]}
68
-          if pr["minutes"] && pr["minutes"].to_i < options["alert_window_in_minutes"].to_i
68
+          if pr["minutes"] && pr["minutes"].to_i < interpolated["alert_window_in_minutes"].to_i
69 69
             vals = vals.merge Hash.from_xml(pr.to_xml)
70 70
             if not_already_in_memory?(vals)
71 71
               create_event(:payload => vals)

+ 3 - 4
app/models/agents/pushbullet_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class PushbulletAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
     cannot_create_events!
7 5
 
@@ -49,10 +47,11 @@ module Agents
49 47
     end
50 48
 
51 49
     private
50
+
52 51
     def query_options(event)
53
-      mo = interpolate_options options, event.payload
52
+      mo = interpolated(event.payload)
54 53
       {
55
-        :basic_auth => {:username =>mo[:api_key], :password=>''},
54
+        :basic_auth => {:username => mo[:api_key], :password => ''},
56 55
         :body => {:device_iden => mo[:device_id], :title => mo[:title], :body => mo[:body], :type => 'note'}
57 56
       }
58 57
     end

+ 24 - 23
app/models/agents/pushover_agent.rb

@@ -58,44 +58,45 @@ module Agents
58 58
 
59 59
     def receive(incoming_events)
60 60
       incoming_events.each do |event|
61
-        message = (event.payload['message'].presence  || event.payload['text'].presence  || options['message']).to_s
61
+        payload_interpolated = interpolated(event.payload)
62
+        message = (event.payload['message'].presence || event.payload['text'].presence || payload_interpolated['message']).to_s
62 63
         if message.present?
63
-            post_params = {
64
-              'token' => options['token'],
65
-              'user' => options['user'],
66
-              'message' => message
67
-            }
64
+          post_params = {
65
+            'token' => payload_interpolated['token'],
66
+            'user' => payload_interpolated['user'],
67
+            'message' => message
68
+          }
68 69
 
69
-            post_params['device'] = event.payload['device'].presence  || options['device']
70
-            post_params['title'] = event.payload['title'].presence  || event.payload['subject'].presence  || options['title']
70
+          post_params['device'] = event.payload['device'].presence || payload_interpolated['device']
71
+          post_params['title'] = event.payload['title'].presence || event.payload['subject'].presence || payload_interpolated['title']
71 72
 
72
-            url = (event.payload['url'].presence  || options['url'] || '').to_s
73
-            url = url.slice 0..512
74
-            post_params['url'] = url
73
+          url = (event.payload['url'].presence || payload_interpolated['url'] || '').to_s
74
+          url = url.slice 0..512
75
+          post_params['url'] = url
75 76
 
76
-            url_title = (event.payload['url_title'].presence  || options['url_title']).to_s
77
-            url_title = url_title.slice 0..100
78
-            post_params['url_title'] = url_title
77
+          url_title = (event.payload['url_title'].presence || payload_interpolated['url_title']).to_s
78
+          url_title = url_title.slice 0..100
79
+          post_params['url_title'] = url_title
79 80
 
80
-            post_params['priority'] = (event.payload['priority'].presence  || options['priority']).to_i
81
+          post_params['priority'] = (event.payload['priority'].presence || payload_interpolated['priority']).to_i
81 82
 
82
-            if event.payload.has_key? 'timestamp'
83
-              post_params['timestamp'] = (event.payload['timestamp']).to_s
84
-            end
83
+          if event.payload.has_key? 'timestamp'
84
+            post_params['timestamp'] = (event.payload['timestamp']).to_s
85
+          end
85 86
 
86
-            post_params['sound'] = (event.payload['sound'].presence  || options['sound']).to_s
87
+          post_params['sound'] = (event.payload['sound'].presence || payload_interpolated['sound']).to_s
87 88
 
88
-            post_params['retry'] = (event.payload['retry'].presence  || options['retry']).to_i
89
+          post_params['retry'] = (event.payload['retry'].presence || payload_interpolated['retry']).to_i
89 90
 
90
-            post_params['expire'] = (event.payload['expire'].presence  || options['expire']).to_i
91
+          post_params['expire'] = (event.payload['expire'].presence || payload_interpolated['expire']).to_i
91 92
 
92
-            send_notification(post_params)
93
+          send_notification(post_params)
93 94
         end
94 95
       end
95 96
     end
96 97
 
97 98
     def working?
98
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
99
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
99 100
     end
100 101
 
101 102
     def send_notification(post_params)

+ 2 - 2
app/models/agents/sentiment_agent.rb

@@ -34,13 +34,13 @@ module Agents
34 34
     end
35 35
 
36 36
     def working?
37
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
37
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
38 38
     end
39 39
 
40 40
     def receive(incoming_events)
41 41
       anew = self.class.sentiment_hash
42 42
       incoming_events.each do |event|
43
-        Utils.values_at(event.payload, options['content']).each do |content|
43
+        Utils.values_at(event.payload, interpolated['content']).each do |content|
44 44
           sent_values = sentiment_values anew, content
45 45
           create_event :payload => { 'content' => content,
46 46
                                      'valence' => sent_values[0],

+ 8 - 7
app/models/agents/shell_command_agent.rb

@@ -15,7 +15,8 @@ module Agents
15 15
 
16 16
       `expected_update_period_in_days` is used to determine if the Agent is working.
17 17
 
18
-      ShellCommandAgent can also act upon received events. These events may contain their own `path` and `command` values. If they do not, ShellCommandAgent will use the configured options. For this reason, please specify defaults even if you are planning to have this Agent to respond to events.
18
+      ShellCommandAgent can also act upon received events. When receiving an event, this Agent's options can interpolate values from the incoming event.
19
+      For example, your command could be defined as `{{cmd}}`, in which case the event's `cmd` property would be used.
19 20
 
20 21
       The resulting event will contain the `command` which was executed, the `path` it was executed under, the `exit_status` of the command, the `errors`, and the actual `output`. ShellCommandAgent will not log an error if the result implies that something went wrong.
21 22
 
@@ -55,25 +56,25 @@ module Agents
55 56
     end
56 57
 
57 58
     def working?
58
-      Agents::ShellCommandAgent.should_run? && event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
59
+      Agents::ShellCommandAgent.should_run? && event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
59 60
     end
60 61
 
61 62
     def receive(incoming_events)
62 63
       incoming_events.each do |event|
63
-        handle(event.payload, event)
64
+        handle(interpolated(event.payload), event)
64 65
       end
65 66
     end
66 67
 
67 68
     def check
68
-      handle(options)
69
+      handle(interpolated)
69 70
     end
70 71
 
71 72
     private
72 73
 
73
-    def handle(opts = options, event = nil)
74
+    def handle(opts, event = nil)
74 75
       if Agents::ShellCommandAgent.should_run?
75
-        command = opts['command'] || options['command']
76
-        path = opts['path'] || options['path']
76
+        command = opts['command']
77
+        path = opts['path']
77 78
 
78 79
         result, errors, exit_status = run_command(path, command)
79 80
 

+ 4 - 5
app/models/agents/slack_agent.rb

@@ -1,6 +1,5 @@
1 1
 module Agents
2 2
   class SlackAgent < Agent
3
-    include LiquidInterpolatable
4 3
     cannot_be_scheduled!
5 4
     cannot_create_events!
6 5
 
@@ -45,20 +44,20 @@ module Agents
45 44
     end
46 45
 
47 46
     def webhook
48
-      options[:webhook].presence || DEFAULT_WEBHOOK
47
+      interpolated[:webhook].presence || DEFAULT_WEBHOOK
49 48
     end
50 49
 
51 50
     def username
52
-      options[:username].presence || DEFAULT_USERNAME
51
+      interpolated[:username].presence || DEFAULT_USERNAME
53 52
     end
54 53
 
55 54
     def slack_notifier
56
-      @slack_notifier ||= Slack::Notifier.new(options[:team_name], options[:auth_token], webhook, username: username)
55
+      @slack_notifier ||= Slack::Notifier.new(interpolated[:team_name], interpolated[:auth_token], webhook, username: username)
57 56
     end
58 57
 
59 58
     def receive(incoming_events)
60 59
       incoming_events.each do |event|
61
-        opts = interpolate_options options, event.payload
60
+        opts = interpolated(event.payload)
62 61
         slack_notifier.ping opts[:message], channel: opts[:channel], username: opts[:username]
63 62
       end
64 63
     end

+ 1 - 1
app/models/agents/stubhub_agent.rb

@@ -35,7 +35,7 @@ module Agents
35 35
     end
36 36
 
37 37
     def url
38
-      options['url']
38
+      interpolated['url']
39 39
     end
40 40
 
41 41
     def check

+ 6 - 8
app/models/agents/translation_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class TranslationAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
 
7 5
     description <<-MD
@@ -30,7 +28,7 @@ module Agents
30 28
     end
31 29
 
32 30
     def working?
33
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
31
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
34 32
     end
35 33
 
36 34
     def translate(text, to, access_token)
@@ -61,16 +59,16 @@ module Agents
61 59
 
62 60
     def receive(incoming_events)
63 61
       auth_uri = URI "https://datamarket.accesscontrol.windows.net/v2/OAuth2-13"
64
-      response = postform auth_uri, :client_id => options['client_id'],
65
-                                    :client_secret => options['client_secret'],
62
+      response = postform auth_uri, :client_id => interpolated['client_id'],
63
+                                    :client_secret => interpolated['client_secret'],
66 64
                                     :scope => "http://api.microsofttranslator.com",
67 65
                                     :grant_type => "client_credentials"
68 66
       access_token = JSON.parse(response.body)["access_token"]
69 67
       incoming_events.each do |event|
70 68
         translated_event = {}
71
-        options['content'].each_pair do |key, value|
72
-          to_be_translated = interpolate_string(value, event.payload)
73
-          translated_event[key] = translate(to_be_translated.first, options['to'], access_token)
69
+        opts = interpolated(event.payload)
70
+        opts['content'].each_pair do |key, value|
71
+          translated_event[key] = translate(value.first, opts['to'], access_token)
74 72
         end
75 73
         create_event :payload => translated_event
76 74
       end

+ 9 - 8
app/models/agents/trigger_agent.rb

@@ -1,7 +1,5 @@
1 1
 module Agents
2 2
   class TriggerAgent < Agent
3
-    include LiquidInterpolatable
4
-
5 3
     cannot_be_scheduled!
6 4
 
7 5
     VALID_COMPARISON_TYPES = %w[regex !regex field<value field<=value field==value field!=value field>=value field>value]
@@ -30,7 +28,7 @@ module Agents
30 28
 
31 29
     def validate_options
32 30
       unless options['expected_receive_period_in_days'].present? && options['rules'].present? &&
33
-          options['rules'].all? { |rule| rule['type'].present? && VALID_COMPARISON_TYPES.include?(rule['type']) && rule['value'].present? && rule['path'].present? }
31
+             options['rules'].all? { |rule| rule['type'].present? && VALID_COMPARISON_TYPES.include?(rule['type']) && rule['value'].present? && rule['path'].present? }
34 32
         errors.add(:base, "expected_receive_period_in_days, message, and rules, with a type, value, and path for every rule, are required")
35 33
       end
36 34
 
@@ -53,12 +51,15 @@ module Agents
53 51
     end
54 52
 
55 53
     def working?
56
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
54
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
57 55
     end
58 56
 
59 57
     def receive(incoming_events)
60 58
       incoming_events.each do |event|
61
-        match = options['rules'].all? do |rule|
59
+
60
+        opts = interpolated(event.payload)
61
+
62
+        match = opts['rules'].all? do |rule|
62 63
           value_at_path = Utils.value_at(event['payload'], rule['path'])
63 64
           rule_values = rule['value']
64 65
           rule_values = [rule_values] unless rule_values.is_a?(Array)
@@ -90,9 +91,9 @@ module Agents
90 91
         if match
91 92
           if keep_event?
92 93
             payload = event.payload.dup
93
-            payload['message'] = interpolate_string(options['message'], event.payload) if options['message'].present?
94
+            payload['message'] = opts['message'] if opts['message'].present?
94 95
           else
95
-            payload = { 'message' => interpolate_string(options['message'], event.payload) }
96
+            payload = { 'message' => opts['message'] }
96 97
           end
97 98
 
98 99
           create_event :payload => payload
@@ -101,7 +102,7 @@ module Agents
101 102
     end
102 103
 
103 104
     def keep_event?
104
-      options['keep_event'] == 'true'
105
+      interpolated['keep_event'] == 'true'
105 106
     end
106 107
   end
107 108
 end

+ 9 - 9
app/models/agents/twilio_agent.rb

@@ -39,18 +39,18 @@ module Agents
39 39
     end
40 40
 
41 41
     def receive(incoming_events)
42
-      @client = Twilio::REST::Client.new options['account_sid'], options['auth_token']
42
+      @client = Twilio::REST::Client.new interpolated['account_sid'], interpolated['auth_token']
43 43
       memory['pending_calls'] ||= {}
44 44
       incoming_events.each do |event|
45 45
         message = (event.payload['message'].presence || event.payload['text'].presence || event.payload['sms'].presence).to_s
46 46
         if message.present?
47
-          if options['receive_call'].to_s == 'true'
47
+          if interpolated(event.payload)['receive_call'].to_s == 'true'
48 48
             secret = SecureRandom.hex 3
49 49
             memory['pending_calls'][secret] = message
50 50
             make_call secret
51 51
           end
52 52
 
53
-          if options['receive_text'].to_s == 'true'
53
+          if interpolated(event.payload)['receive_text'].to_s == 'true'
54 54
             message = message.slice 0..160
55 55
             send_message message
56 56
           end
@@ -59,19 +59,19 @@ module Agents
59 59
     end
60 60
 
61 61
     def working?
62
-      last_receive_at && last_receive_at > options['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
62
+      last_receive_at && last_receive_at > interpolated['expected_receive_period_in_days'].to_i.days.ago && !recent_error_logs?
63 63
     end
64 64
 
65 65
     def send_message(message)
66
-      @client.account.sms.messages.create :from => options['sender_cell'],
67
-                                          :to => options['receiver_cell'],
66
+      @client.account.sms.messages.create :from => interpolated['sender_cell'],
67
+                                          :to => interpolated['receiver_cell'],
68 68
                                           :body => message
69 69
     end
70 70
 
71 71
     def make_call(secret)
72
-      @client.account.calls.create :from => options['sender_cell'],
73
-                                   :to => options['receiver_cell'],
74
-                                   :url => post_url(options['server_url'], secret)
72
+      @client.account.calls.create :from => interpolated['sender_cell'],
73
+                                   :to => interpolated['receiver_cell'],
74
+                                   :url => post_url(interpolated['server_url'], secret)
75 75
     end
76 76
 
77 77
     def post_url(server_url, secret)

+ 2 - 3
app/models/agents/twitter_publish_agent.rb

@@ -3,7 +3,6 @@ require "twitter"
3 3
 module Agents
4 4
   class TwitterPublishAgent < Agent
5 5
     include TwitterConcern
6
-    include LiquidInterpolatable
7 6
 
8 7
     cannot_be_scheduled!
9 8
 
@@ -26,7 +25,7 @@ module Agents
26 25
     end
27 26
 
28 27
     def working?
29
-      event_created_within?(options['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs?
28
+      event_created_within?(interpolated['expected_update_period_in_days']) && most_recent_event && most_recent_event.payload['success'] == true && !recent_error_logs?
30 29
     end
31 30
 
32 31
     def default_options
@@ -42,7 +41,7 @@ module Agents
42 41
         incoming_events = incoming_events.first(20)
43 42
       end
44 43
       incoming_events.each do |event|
45
-        tweet_text = interpolate_string(options['message'], event.payload)
44
+        tweet_text = interpolated(event.payload)['message']
46 45
         begin
47 46
           tweet = publish_tweet tweet_text
48 47
           create_event :payload => {

+ 5 - 5
app/models/agents/twitter_stream_agent.rb

@@ -65,7 +65,7 @@ module Agents
65 65
     end
66 66
 
67 67
     def working?
68
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
68
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
69 69
     end
70 70
 
71 71
     def default_options
@@ -80,7 +80,7 @@ module Agents
80 80
       filter = lookup_filter(filter)
81 81
 
82 82
       if filter
83
-        if options['generate'] == "counts"
83
+        if interpolated['generate'] == "counts"
84 84
           # Avoid memory pollution by reloading the Agent.
85 85
           agent = Agent.find(id)
86 86
           agent.memory['filter_counts'] ||= {}
@@ -95,7 +95,7 @@ module Agents
95 95
     end
96 96
 
97 97
     def check
98
-      if options['generate'] == "counts" && memory['filter_counts'] && memory['filter_counts'].length > 0
98
+      if interpolated['generate'] == "counts" && memory['filter_counts'] && memory['filter_counts'].length > 0
99 99
         memory['filter_counts'].each do |filter, count|
100 100
           create_event :payload => { 'filter' => filter, 'count' => count, 'time' => Time.now.to_i }
101 101
         end
@@ -106,7 +106,7 @@ module Agents
106 106
     protected
107 107
 
108 108
     def lookup_filter(filter)
109
-      options['filters'].each do |known_filter|
109
+      interpolated['filters'].each do |known_filter|
110 110
         if known_filter == filter
111 111
           return filter
112 112
         elsif known_filter.is_a?(Array)
@@ -119,7 +119,7 @@ module Agents
119 119
 
120 120
     def remove_unused_keys!(agent, base)
121 121
       if agent.memory[base]
122
-        (agent.memory[base].keys - agent.options['filters'].map {|f| f.is_a?(Array) ? f.first.to_s : f.to_s }).each do |removed_key|
122
+        (agent.memory[base].keys - agent.interpolated['filters'].map {|f| f.is_a?(Array) ? f.first.to_s : f.to_s }).each do |removed_key|
123 123
           agent.memory[base].delete(removed_key)
124 124
         end
125 125
       end

+ 5 - 5
app/models/agents/twitter_user_agent.rb

@@ -51,7 +51,7 @@ module Agents
51 51
     default_schedule "every_1h"
52 52
 
53 53
     def working?
54
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
54
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
55 55
     end
56 56
 
57 57
     def default_options
@@ -76,15 +76,15 @@ module Agents
76 76
     end
77 77
 
78 78
     def starting_at
79
-      if options[:starting_at].present?
80
-        Time.parse(options[:starting_at]) rescue created_at
79
+      if interpolated[:starting_at].present?
80
+        Time.parse(interpolated[:starting_at]) rescue created_at
81 81
       else
82 82
         created_at
83 83
       end
84 84
     end
85 85
 
86 86
     def include_retweets?
87
-      options[:include_retweets] != "false"
87
+      interpolated[:include_retweets] != "false"
88 88
     end
89 89
 
90 90
     def check
@@ -93,7 +93,7 @@ module Agents
93 93
       opts.merge! :since_id => since_id unless since_id.nil?
94 94
 
95 95
       # http://rdoc.info/gems/twitter/Twitter/REST/Timelines#user_timeline-instance_method
96
-      tweets = twitter.user_timeline(options['username'], opts)
96
+      tweets = twitter.user_timeline(interpolated['username'], opts)
97 97
 
98 98
       tweets.each do |tweet|
99 99
         if tweet.created_at >= starting_at

+ 7 - 7
app/models/agents/weather_agent.rb

@@ -51,11 +51,11 @@ module Agents
51 51
     default_schedule "8pm"
52 52
 
53 53
     def working?
54
-      event_created_within?((options['expected_update_period_in_days'].presence || 2).to_i) && !recent_error_logs?
54
+      event_created_within?((interpolated['expected_update_period_in_days'].presence || 2).to_i) && !recent_error_logs?
55 55
     end
56 56
 
57 57
     def key_setup?
58
-      options['api_key'].present? && options['api_key'] != "your-key"
58
+      interpolated['api_key'].present? && interpolated['api_key'] != "your-key"
59 59
     end
60 60
 
61 61
     def default_options
@@ -69,15 +69,15 @@ module Agents
69 69
     end
70 70
 
71 71
     def service
72
-      options["service"].presence || "wunderground"
72
+      interpolated["service"].presence || "wunderground"
73 73
     end
74 74
 
75 75
     def which_day
76
-      (options["which_day"].presence || 1).to_i
76
+      (interpolated["which_day"].presence || 1).to_i
77 77
     end
78 78
 
79 79
     def location
80
-      options["location"].presence || options["zipcode"]
80
+      interpolated["location"].presence || interpolated["zipcode"]
81 81
     end
82 82
 
83 83
     def validate_options
@@ -89,12 +89,12 @@ module Agents
89 89
     end
90 90
 
91 91
     def wunderground
92
-      Wunderground.new(options['api_key']).forecast_for(location)['forecast']['simpleforecast']['forecastday'] if key_setup?
92
+      Wunderground.new(interpolated['api_key']).forecast_for(location)['forecast']['simpleforecast']['forecastday'] if key_setup?
93 93
     end
94 94
 
95 95
     def forecastio
96 96
       if key_setup?
97
-        ForecastIO.api_key = options['api_key']
97
+        ForecastIO.api_key = interpolated['api_key']
98 98
         lat, lng = location.split(',')
99 99
         ForecastIO.forecast(lat,lng)['daily']['data']
100 100
       end

+ 4 - 4
app/models/agents/webhook_agent.rb

@@ -27,7 +27,7 @@ module Agents
27 27
     event_description do
28 28
       <<-MD
29 29
         The event payload is base on the value of the `payload_path` option,
30
-        which is set to `#{options['payload_path']}`.
30
+        which is set to `#{interpolated['payload_path']}`.
31 31
       MD
32 32
     end
33 33
 
@@ -40,7 +40,7 @@ module Agents
40 40
     def receive_web_request(params, method, format)
41 41
       secret = params.delete('secret')
42 42
       return ["Please use POST requests only", 401] unless method == "post"
43
-      return ["Not Authorized", 401] unless secret == options['secret']
43
+      return ["Not Authorized", 401] unless secret == interpolated['secret']
44 44
 
45 45
       create_event(:payload => payload_for(params))
46 46
 
@@ -48,7 +48,7 @@ module Agents
48 48
     end
49 49
 
50 50
     def working?
51
-      event_created_within?(options['expected_receive_period_in_days']) && !recent_error_logs?
51
+      event_created_within?(interpolated['expected_receive_period_in_days']) && !recent_error_logs?
52 52
     end
53 53
 
54 54
     def validate_options
@@ -58,7 +58,7 @@ module Agents
58 58
     end
59 59
 
60 60
     def payload_for(params)
61
-      Utils.value_at(params, options['payload_path']) || {}
61
+      Utils.value_at(params, interpolated['payload_path']) || {}
62 62
     end
63 63
   end
64 64
 end

+ 22 - 22
app/models/agents/website_agent.rb

@@ -55,11 +55,11 @@ module Agents
55 55
     MD
56 56
 
57 57
     event_description do
58
-      "Events will have the fields you specified.  Your options look like:\n\n    #{Utils.pretty_print options['extract']}"
58
+      "Events will have the fields you specified.  Your options look like:\n\n    #{Utils.pretty_print interpolated['extract']}"
59 59
     end
60 60
 
61 61
     def working?
62
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
62
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
63 63
     end
64 64
 
65 65
     def default_options
@@ -125,7 +125,7 @@ module Agents
125 125
     end
126 126
 
127 127
     def check
128
-      check_url options['url']
128
+      check_url interpolated['url']
129 129
     end
130 130
 
131 131
     def check_url(in_url)
@@ -136,7 +136,7 @@ module Agents
136 136
         response = faraday.get(url)
137 137
         if response.success?
138 138
           body = response.body
139
-          if (encoding = options['force_encoding']).present?
139
+          if (encoding = interpolated['force_encoding']).present?
140 140
             body = body.encode(Encoding::UTF_8, encoding)
141 141
           end
142 142
           doc = parse(body)
@@ -148,7 +148,7 @@ module Agents
148 148
             end
149 149
           else
150 150
             output = {}
151
-            options['extract'].each do |name, extraction_details|
151
+            interpolated['extract'].each do |name, extraction_details|
152 152
               if extraction_type == "json"
153 153
                 result = Utils.values_at(doc, extraction_details['path'])
154 154
                 log "Extracting #{extraction_type} at #{extraction_details['path']}: #{result}"
@@ -181,17 +181,17 @@ module Agents
181 181
               output[name] = result
182 182
             end
183 183
 
184
-            num_unique_lengths = options['extract'].keys.map { |name| output[name].length }.uniq
184
+            num_unique_lengths = interpolated['extract'].keys.map { |name| output[name].length }.uniq
185 185
 
186 186
             if num_unique_lengths.length != 1
187
-              error "Got an uneven number of matches for #{options['name']}: #{options['extract'].inspect}"
187
+              error "Got an uneven number of matches for #{interpolated['name']}: #{interpolated['extract'].inspect}"
188 188
               return
189 189
             end
190 190
 
191 191
             old_events = previous_payloads num_unique_lengths.first
192 192
             num_unique_lengths.first.times do |index|
193 193
               result = {}
194
-              options['extract'].keys.each do |name|
194
+              interpolated['extract'].keys.each do |name|
195 195
                 result[name] = output[name][index]
196 196
                 if name.to_s == 'url'
197 197
                   result[name] = (response.env[:url] + result[name]).to_s
@@ -223,11 +223,11 @@ module Agents
223 223
     # If mode is set to 'on_change', this method may return false and update an existing
224 224
     # event to expire further in the future.
225 225
     def store_payload!(old_events, result)
226
-      if !options['mode'].present?
226
+      if !interpolated['mode'].present?
227 227
         return true
228
-      elsif options['mode'].to_s == "all"
228
+      elsif interpolated['mode'].to_s == "all"
229 229
         return true
230
-      elsif options['mode'].to_s == "on_change"
230
+      elsif interpolated['mode'].to_s == "on_change"
231 231
         result_json = result.to_json
232 232
         old_events.each do |old_event|
233 233
           if old_event.payload.to_json == result_json
@@ -238,12 +238,12 @@ module Agents
238 238
         end
239 239
         return true
240 240
       end
241
-      raise "Illegal options[mode]: " + options['mode'].to_s
241
+      raise "Illegal options[mode]: " + interpolated['mode'].to_s
242 242
     end
243 243
 
244 244
     def previous_payloads(num_events)
245
-      if options['uniqueness_look_back'].present?
246
-        look_back = options['uniqueness_look_back'].to_i
245
+      if interpolated['uniqueness_look_back'].present?
246
+        look_back = interpolated['uniqueness_look_back'].to_i
247 247
       else
248 248
         # Larger of UNIQUENESS_FACTOR * num_events and UNIQUENESS_LOOK_BACK
249 249
         look_back = UNIQUENESS_FACTOR * num_events
@@ -251,18 +251,18 @@ module Agents
251 251
           look_back = UNIQUENESS_LOOK_BACK
252 252
         end
253 253
       end
254
-      events.order("id desc").limit(look_back) if options['mode'].present? && options['mode'].to_s == "on_change"
254
+      events.order("id desc").limit(look_back) if interpolated['mode'].present? && interpolated['mode'].to_s == "on_change"
255 255
     end
256 256
 
257 257
     def extract_full_json?
258
-      !options['extract'].present? && extraction_type == "json"
258
+      !interpolated['extract'].present? && extraction_type == "json"
259 259
     end
260 260
 
261 261
     def extraction_type
262
-      (options['type'] || begin
263
-        if options['url'] =~ /\.(rss|xml)$/i
262
+      (interpolated['type'] || begin
263
+        if interpolated['url'] =~ /\.(rss|xml)$/i
264 264
           "xml"
265
-        elsif options['url'] =~ /\.json$/i
265
+        elsif interpolated['url'] =~ /\.json$/i
266 266
           "json"
267 267
         else
268 268
           "html"
@@ -295,7 +295,7 @@ module Agents
295 295
       @faraday ||= Faraday.new { |builder|
296 296
         builder.headers = headers if headers.length > 0
297 297
 
298
-        if (user_agent = options['user_agent']).present?
298
+        if (user_agent = interpolated['user_agent']).present?
299 299
           builder.headers[:user_agent] = user_agent
300 300
         end
301 301
 
@@ -318,7 +318,7 @@ module Agents
318 318
     end
319 319
 
320 320
     def basic_auth_credentials
321
-      case value = options['basic_auth']
321
+      case value = interpolated['basic_auth']
322 322
       when nil, ''
323 323
         return nil
324 324
       when Array
@@ -330,7 +330,7 @@ module Agents
330 330
     end
331 331
 
332 332
     def headers
333
-      options['headers'].presence || {}
333
+      interpolated['headers'].presence || {}
334 334
     end
335 335
   end
336 336
 end

+ 3 - 3
app/models/agents/weibo_publish_agent.rb

@@ -21,13 +21,13 @@ module Agents
21 21
 
22 22
     def validate_options
23 23
       unless options['uid'].present? &&
24
-        options['expected_update_period_in_days'].present?
24
+             options['expected_update_period_in_days'].present?
25 25
         errors.add(:base, "expected_update_period_in_days and uid are required")
26 26
       end
27 27
     end
28 28
 
29 29
     def working?
30
-      event_created_within?(options['expected_update_period_in_days']) && most_recent_event.payload['success'] == true && !recent_error_logs?
30
+      event_created_within?(interpolated['expected_update_period_in_days']) && most_recent_event.payload['success'] == true && !recent_error_logs?
31 31
     end
32 32
 
33 33
     def default_options
@@ -47,7 +47,7 @@ module Agents
47 47
         incoming_events = incoming_events.first(20)
48 48
       end
49 49
       incoming_events.each do |event|
50
-        tweet_text = Utils.value_at(event.payload, options['message_path'])
50
+        tweet_text = Utils.value_at(event.payload, interpolated(event.payload)['message_path'])
51 51
         if event.agent.type == "Agents::TwitterUserAgent"
52 52
           tweet_text = unwrap_tco_urls(tweet_text, event.payload)
53 53
         end

+ 3 - 3
app/models/agents/weibo_user_agent.rb

@@ -71,13 +71,13 @@ module Agents
71 71
 
72 72
     def validate_options
73 73
       unless options['uid'].present? &&
74
-        options['expected_update_period_in_days'].present?
74
+             options['expected_update_period_in_days'].present?
75 75
         errors.add(:base, "expected_update_period_in_days and uid are required")
76 76
       end
77 77
     end
78 78
 
79 79
     def working?
80
-      event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs?
80
+      event_created_within?(interpolated['expected_update_period_in_days']) && !recent_error_logs?
81 81
     end
82 82
 
83 83
     def default_options
@@ -92,7 +92,7 @@ module Agents
92 92
 
93 93
     def check
94 94
       since_id = memory['since_id'] || nil
95
-      opts = {:uid => options['uid'].to_i}
95
+      opts = {:uid => interpolated['uid'].to_i}
96 96
       opts.merge! :since_id => since_id unless since_id.nil?
97 97
 
98 98
       # http://open.weibo.com/wiki/2/statuses/user_timeline/en

+ 9 - 6
spec/models/agent_spec.rb

@@ -121,13 +121,16 @@ describe Agent do
121 121
       stub(Agents::CannotBeScheduled).valid_type?("Agents::CannotBeScheduled") { true }
122 122
     end
123 123
 
124
-    let(:new_instance) do
125
-      agent = Agents::SomethingSource.new(:name => "some agent")
126
-      agent.user = users(:bob)
127
-      agent
128
-    end
124
+    describe Agents::SomethingSource do
125
+      let(:new_instance) do
126
+        agent = Agents::SomethingSource.new(:name => "some agent")
127
+        agent.user = users(:bob)
128
+        agent
129
+      end
129 130
 
130
-    it_behaves_like HasGuid
131
+      it_behaves_like LiquidInterpolatable
132
+      it_behaves_like HasGuid
133
+    end
131 134
 
132 135
     describe ".default_schedule" do
133 136
       it "stores the default on the class" do

+ 0 - 2
spec/models/agents/data_output_agent_spec.rb

@@ -3,8 +3,6 @@
3 3
 require 'spec_helper'
4 4
 
5 5
 describe Agents::DataOutputAgent do
6
-  it_behaves_like LiquidInterpolatable
7
-
8 6
   let(:agent) do
9 7
     _agent = Agents::DataOutputAgent.new(:name => 'My Data Output Agent')
10 8
     _agent.options = _agent.default_options.merge('secrets' => ['secret1', 'secret2'], 'events_to_show' => 2)

+ 0 - 2
spec/models/agents/hipchat_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::HipchatAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before(:each) do
7 5
     @valid_params = {
8 6
                       'auth_token' => 'token',

+ 0 - 2
spec/models/agents/human_task_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::HumanTaskAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before do
7 5
     @checker = Agents::HumanTaskAgent.new(:name => "my human task agent")
8 6
     @checker.options = @checker.default_options

+ 0 - 2
spec/models/agents/jabber_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::JabberAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   let(:sent) { [] }
7 5
   let(:config) {
8 6
     {

+ 0 - 2
spec/models/agents/peak_detector_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::PeakDetectorAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before do
7 5
     @valid_params = {
8 6
         'name' => "my peak detector agent",

+ 0 - 2
spec/models/agents/pushbullet_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::PushbulletAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before(:each) do
7 5
     @valid_params = {
8 6
                       'api_key' => 'token',

+ 4 - 3
spec/models/agents/shell_command_agent_spec.rb

@@ -17,7 +17,7 @@ describe Agents::ShellCommandAgent do
17 17
     @event = Event.new
18 18
     @event.agent = agents(:jane_weather_agent)
19 19
     @event.payload = {
20
-      :command => "ls"
20
+      :cmd => "ls"
21 21
     }
22 22
     @event.save!
23 23
 
@@ -78,13 +78,14 @@ describe Agents::ShellCommandAgent do
78 78
 
79 79
   describe "#receive" do
80 80
     before do
81
-      stub(@checker).run_command(@valid_path, @event.payload[:command]) { ["fake ls output", "", 0] }
81
+      stub(@checker).run_command(@valid_path, @event.payload[:cmd]) { ["fake ls output", "", 0] }
82 82
     end
83 83
 
84 84
     it "creates events" do
85
+      @checker.options[:command] = "{{cmd}}"
85 86
       @checker.receive([@event])
86 87
       Event.last.payload[:path].should == @valid_path
87
-      Event.last.payload[:command].should == @event.payload[:command]
88
+      Event.last.payload[:command].should == @event.payload[:cmd]
88 89
       Event.last.payload[:output].should == "fake ls output"
89 90
     end
90 91
 

+ 0 - 2
spec/models/agents/slack_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::SlackAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before(:each) do
7 5
     @valid_params = {
8 6
                       'auth_token' => 'token',

+ 0 - 2
spec/models/agents/translation_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::TranslationAgent do
4
-    it_behaves_like LiquidInterpolatable
5
-
6 4
     before do
7 5
         @valid_params = {
8 6
             :name    => "somename",

+ 0 - 2
spec/models/agents/trigger_agent_spec.rb

@@ -1,8 +1,6 @@
1 1
 require 'spec_helper'
2 2
 
3 3
 describe Agents::TriggerAgent do
4
-  it_behaves_like LiquidInterpolatable
5
-
6 4
   before do
7 5
     @valid_params = {
8 6
       'name' => "my trigger agent",

+ 2 - 1
spec/support/shared_examples/liquid_interpolatable.rb

@@ -28,7 +28,7 @@ shared_examples_for LiquidInterpolatable do
28 28
       }
29 29
     end
30 30
 
31
-    it "hsould work with arrays", focus: true do
31
+    it "should work with arrays", focus: true do
32 32
       @checker.options = {"value" => ["{{variable}}", "Much array", "Hey, {{hello_world}}"]}
33 33
       @checker.interpolate_options(@checker.options, @event.payload).should == {
34 34
         "value" => ["hello", "Much array", "Hey, Hello world"]
@@ -53,6 +53,7 @@ shared_examples_for LiquidInterpolatable do
53 53
       @checker.interpolate_string("{{variable}} you", @event.payload).should == "hello you"
54 54
     end
55 55
   end
56
+
56 57
   describe "liquid tags" do
57 58
     it "should work with existing credentials" do
58 59
       @checker.interpolate_string("{% credential aws_key %}", {}).should == '2222222222-jane'