Day 18 – Actions Before and After Foreach Looping

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 <<
    author "Mike Grace"
    logging on

  global {
    dataset kynetxAppADay:RSS <- "";

  rule run_once_before_loop {
    select when pageview ".*"

  rule process_rss_feed_in_loop {
    select when pageview ".*"
    foreach rss:items(kynetxAppADay) setting (post)
    pre {
      link = post.pick("$$t");
      title = post.pick("$..title.$t");
      description = post.pick("$..description.$t");
      content =<<
          <p><a href="#{link}">#{title}</a></p>
      append("body", content);

  rule run_once_after_loop {
    select when pageview ".*"
      append("body", "<h1>All done processing RSS feed for XKCD! :D</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 with bookmarklet

App run on with bookmarklet

Bottom of page on after app has run with bookmarklet

Get the bookmarklet to try it out yourself!

Gratuitous day 16 Grace face

This entry was posted in Kynetx. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s