Day 19 – Regular Expression Matching In KRL

Sometimes in apps you want to check to see if a string is found in some text and react accordingly.

ruleset a60x511 {
  meta {
    name "Regex-match-test"
    description <<
      Regex-match-test
    >>
    author "Mike Grace"
    logging on
  }

  rule check_for_match {
    select when pageview ".*"
    {
      emit <|
        $K(".stream-item").live("click", function() {
          app = KOBJ.get_application("a60x511");
          var tweetText = $K(this).find(".tweet-text").text();
          app.raise_event("check_clicked_tweet", {"tweetText":tweetText});
        });
      |>;
    }
  }

  rule check_clicked_tweet {
    select when web check_clicked_tweet
    pre {
      tweetText = event:param("tweetText");
      loveFound = tweetText.match(re/love/i);
      heart =<<
        <img src="http://mikegrace.s3.amazonaws.com/kynetx-app-a-day/heart.png"/>
      >>;
    }
    if (loveFound) then {
      notify("#{heart} Found Love in", tweetText) with sticky = true;
    }
    notfired {
      raise explicit event love_not_found
        with tweetText = tweetText;
    }
  }

  rule love_not_found {
    select when explicit love_not_found
    pre {
      tweetText = event:param("tweetText");
    }
    {
      notify(": ( Love not found in", tweetText) with sticky = true;
    }
  }
}
  • 15 use jQuery ‘live’ function because new tweets load up on the page all the time
  • 15-19 when a tweet is clicked on get the text of the tweet and raise an event to process the text of the tweet
  • 25 select on web event of ‘check_clicked_tweet’
  • 27 get tweet text from raised event
  • 28 check to see if the word ‘love’ is found in the tweet using the match operator
  • 33 if the word ‘love’ is found the execute the action block
  • 36 if the action block did not execute because the word ‘love’ wasn’t found in the tweet then raise an explicit event ‘love_not_found’

Clicking on several tweets on twitter.com/MikeGrace after app was run with bookmarklet

Get the bookmarklet to try it out yourself!

Gratuitous day 19 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:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s