A while ago, there was an app that I was building that I wanted to process a bunch of data from a feed in a foreach loop and then wanted to call an action once after the foreach loop was done. I was flustered for a while on how to do this since raising an explicit event in the postlude of the foreach would run the raised event rule once for each time through the foreach loop. I then realized that because rules run in the order they are written for an event, I could just write a rule directly after the looping foreach rule that selected on the same event and would execute right after the foreach loop was done. Smashing!
ruleset a60x510 {
meta {
name "one-action-after-a-loop"
description <<
one-action-after-a-loop
>>
author "Mike Grace"
logging on
}
global {
dataset kynetxAppADay:RSS <- "http://xkcd.com/rss.xml";
}
rule run_once_before_loop {
select when pageview ".*"
{
replace_inner("body","");
}
}
rule process_rss_feed_in_loop {
select when pageview ".*"
foreach rss:items(kynetxAppADay) setting (post)
pre {
link = post.pick("$..link.$t");
title = post.pick("$..title.$t");
description = post.pick("$..description.$t");
content =<<
<div>
<p><a href="#{link}">#{title}</a></p>
<p>#{description}</p>
</div>
>>;
}
{
append("body", content);
}
}
rule run_once_after_loop {
select when pageview ".*"
{
append("body", "<h1>All done processing RSS feed for XKCD!
</h1>");
}
}
}
- 12 get XKCD RSS feed to process in foreach loop
- 15-20 rule that will run once before the foreach loop that cleans up the page
- 23 foreach looping rule selects on all pageviews
- 24 loop through each RSS feed item using the RSS feed function
- 25-35 get data out of individual feed items and build HTML
- 41-46 rule that selects on the same event as the foreach looping rule that will run once after the foreach is done looping through the XKCD RSS feed
Before app is run on example.com with bookmarklet
App run on example.com with bookmarklet
Bottom of page on example.com after app has run with bookmarklet
Get the bookmarklet to try it out yourself!
Gratuitous day 16 Grace face



