Groovy snippets

Jul 20

I like the simplicity of languages like Ruby and JavaScript. In both of these languages, you can do something similar to:

foo = bar || "default"

This actually assigns either bar (if it is truthy), or "default" to foo.

Sadly, with Java and Groovy, foo will actually have either true or false as a value. Behold, there is a way to do the same thing with Groovy:

foo = bar ?: "default"

It’s kind of a play on the ternary operator.

This means I can reduce this code

User currentUser = User.findByName(user)

if (!currentUser) {
    currentUser = new User(name: user)
    currentUser.save()
}

session.user = currentUser

to the one liner:

session.user = User.findByName(user) ?: new User(name: user).save()

Leveraging Twitter's API and Google's JS Library API

May 28

So, in the past half hour I’ve been working on getting the widget at the top-right working. I like it better than the badges twitter provides.

It makes use of the Twitter API, and Google’s recently launched JS Library API.

Here’s the code (or you can look at the bottom of the page source):

If you want to re-use it, replace twitterUsername with your twitter username.


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
  var twitterUsername = 'broady';

  $(document).ready(function() {
    $.ajax({
      dataType: 'jsonp',
      url: "http://twitter.com/statuses/user_timeline/" + twitterUsername + ".json?callback=twitterCallback"
    });
  });

  function twitterCallback(data) {
    var found = false;
    $.each(data, function(){
      if (this["text"].indexOf('@') != 0 && !found) {
        $('#twitter').text(this["text"]);
        found = true;
      }
    });
  }
</script>