|
module Agents
class EventFormattingAgent < Agent
cannot_be_scheduled!
description <<-MD
Event Formatting Agent allows you to format your events in any way you prefer.
For example if you have an event like
{
:high => {
:celsius => "18",
:fahreinheit => "64"
},
:conditions => "Rain showers",
:data => "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
And other agents which are receiving this event, say, Twilio Agent expects `message` key , and Digest Email Agent which expects a `subject` key, then you can reformat this event by filling `Instructions` in the following way.
message => "Today's conditions look like <$.conditions> and high temperaure is going to be <$.high.celsius> degree Celsius.""
subject => "$.data"
JSONPaths must be between < and > . Make sure you dont use this symbols anywhere else. You can add as many keys as you like.
Event generated by Event Formatting Agent will be like
{
:message => "Today's conditions look like Rain showers and high temperaure is going to be 18 degree Celsius"
:subject => "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
`Mode` can only be `merge` or `clean`. If you want to retain original contents of events and only add add new keys, then use `merge` mode else use `clean` mode.
MD
event_description <<-MD
User defined
MD
def validate_options
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?
end
def default_options
{
:instructions => {
:message => "You received a text <$.text> from <$.fields.from>",
:content => "Looks like the weather is going to be <$.fields.weather>"},
:mode => "clean",
:skip_agent => "false",
:skip_created_at => "false"
}
end
def working?
true
end
def value_constructor(value,payload)
value.gsub(/<[^>]+>/).each {|jsonpath| Utils.values_at(payload,jsonpath[1..-2]).first.to_s}
end
def receive(incoming_events)
incoming_events.each do |event|
formatted_event = options[:mode].to_s == "merge" ? event.payload : {}
options[:instructions].each_pair {|key,value| formatted_event[key] = value_constructor value, event.payload}
formatted_event[:agent] = Agent.find(event.agent_id).type.slice!(8..-1) unless options[:skip_agent].to_s == "true"
formatted_event[:created_at] = event.created_at unless options[:skip_created_at].to_s == "true"
create_event :payload => formatted_event
end
end
end
end
|