Steve Levine

Archive for the ‘Development’ tag

RubyMine 2 Debugging Issue Resolved

without comments

If you are trying to debug Ruby code in RubyMine 2 IDE, but are having difficulties such as, the IDE freezes after you try to step in, step over, or step next and are wondering if your configuration is wrong? It is not, if you happen to have installed the ruby-debug-ide19 gem from the command line (not from IDE), you need to patch the actual gem code to get things working nicely.

  1. Open the following file with your favorite text editor (part of ruby-debug-ide19 gem)
  2. $GEM_HOME/ruby-debug-ide19-0.4.12/lib/ruby-debug/command.rb
  3. Add the following code at line ~120 (look below for full code location):
  4. return "" if str == "$FILENAME"
  5. After the modifications, the code should look like:
  6.         def debug_eval(str, b = get_binding)
            begin str = str.to_s
            return "" if str == "$FILENAME"
            max_time = 10
           

Thats it, you should be able to debug your Rails/Ruby code in RubyMine without issues.

This entry was posted by Steve on Saturday, January 23rd, 2010 at 3:27 pm and is filed under: , , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

With Grape, Groovy Is On Par with Native Scripting Languages

with 18 comments

If you haven’t heard, the latest version of Groovy was released this week and included with it, among many other great features, was Grape (Groovy Advanced Packaging Engine). Grape is an annotation based dependency management system that provides functionality similar to that of Maven and Ivy with one clear advantage, namely, no build file.

If Grape doesn’t use a build file, how does it know what dependencies are necessary to run the code? Does it figure it out for you on the fly? Unfortunately, it is not that smart (yet), perhaps the next release. If it doesn’t figure it out for you, then how do you specify your dependencies? You configure your dependencies by using the@Grapes or @Grab annotations.

What is so good about being able to configure your dependencies via annotations?

If you are working with Groovy scripts, it frees you up from having to worry about dependency management and allows you to focus more on what the script needs to do much like when working with other scripting languages like Ruby or Perl. In order to clearly demonstrate the advantages of Grape, lets walk through an example.

The problem
Trying to keep up with my ever changing IP address after switching ISP’s earlier this year. There are several services running at my home that I need access to on a daily basis. If my IP changes over night, after a brown out, or for some other reason, I need to know about it asap.

In order to keep up with my IP address, I wrote a set of scripts that perform the following:

  • Obtains the current IP address of the server where it is running
  • Looks up the most recent IP address of the server in a log file
  • If the current IP address is different that the most recent IP address:
    • Updates the log file with the current IP address
    • Send the new IP address in a customizable email to a configurable address
  • If the IP address’s are the same, it does nothing.

The Solution
It took a total of three Groovy classes/scripts to solve this problem. We are not going to get in to the details of the solution because I want to stay focused on Grape.

You can find all of the code discussed in this post on github. Please feel free to download and use it. Feedback is welcome as well.

This simple Groovy class first connects to a mail server, and then sends the change of address message.

import javax.mail.Session
import javax.mail.Message
import javax.mail.internet.MimeMessage
import javax.mail.internet.InternetAddress

@Grapes([
  @Grab(group = 'javax.activation', module = 'activation', version = '1.1'),
  @Grab(group = 'javax.mail', module = 'mail', version = '1.4')
])

class Mailer {

  static def s_config = new ConfigSlurper("message").parse(new File('MailProperties.groovy').toURL())

  static def deliverIpAddressChangeMessage(ipAddress) {
    def subject = "IP Address Changed to ${ipAddress}"
    def message = "IP Address changed to ${ipAddress}.\nPlease update your configurations."
    sendMail("${s_config.message.to}".toString(), "${s_config.message.from}".toString(), subject, message)
  }
  //...
 }

Download Source: Mailer.groovy

The most interesting things to pay attention to are:

  • The @Grapes block after all of the imports, you can see this groovy class depends on javax.activation and javax.mail jars.
  • Thanks to Grapes, you can compile this class simply by invoking groovyc Mailer.groovy as opposed to having to configure either Maven, Gant, Ant, or some other build tool to manage the dependencies and classpath for you.
  • What’s the big deal? Read more to find out!

This next code snipped represents the “main” entry point of my solution. It simply obtains the current IP address of the machine it is running on, checks the current address against the most recent known address stored in a log file, and then uses the previous class to send an email if the IP address has changed.

#!/usr/bin/env groovy

// IP Address Regex http://www.regular-expressions.info/examples.html
currentIp = ("http://whatsmyip.us/".toURL().text =~ /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/)[0]

println currentIp

def ipLog = new File("ip-log.txt")

recentIp = ipLog.readLines().last().tokenize(",").last().trim()

if (currentIp != recentIp) {
  Mailer.deliverIpAddressChangeMessage currentIp
  println "IP Address has changed, it is now: ${currentIp}. Sending Message."
  ipLog << "${new Date()}, ${currentIp}\n"
}

Download Source: whatsMyIp.groovy

The most interesting thing to pay attention to in this script is:

  • The #!/usr/bin/env groovy on the first line on the script.
  • This line enables the script to be called directly from the command line like: ./whatsMyIp.groovy instead of groovy whatsMyIp.groovy

The Big Deal!
If Grape didn’t exist the only way to invoke this script would be to invoke it with a build tool such as Maven, GAnt, or some other. If a build tool didn’t suit you then you would have to invoke groovy -classpath=/path/activation.jar... and manage the dependencies there. Both of these solutions work fine, but are clunky.

If you were to solve this problem using a language such as Ruby, you would not have to worry about dependency management since Ruby is so closely integrated with the OS. You would simply run gem install some gem, and this would install the dependencies at the OS level. Thus allowing you to focus on your script and letting the Ruby runtime focus on the dependencies. Invoking ./someScript.rb is common in Ruby.

Grape gives Groovy scripts the same clean dependency abstraction. It is possible to invoke ./whatsMyIp.groovy without having to worry about any dependency management. Once the groovy runtime comes across the Grape annotations, it loads the dependencies on demand freeing the Groovy script from having to be wrapped with a dependency management layer.

This is a huge deal because now simple Groovy scripts can leverage the entire Java ecosystem from the command line without having to wrap the invocation with a build tool. Groovy Scripts are now clean, simple, and easy. I hope this inspires you to go out and convert some Ruby or Perl script to Groovy.

This entry was posted by Steve on Thursday, December 24th, 2009 at 2:31 pm and is filed under: , , , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Scala Sugar – Iteration

with one comment

In this second installment of Scala Sugar, lets put the lists that we created in the previous post to use.

How do we typically interact with lists when writing non-trivial programs? We iterate over them! With that being said, lets explore how iteration in Scala compares with iteration in Java.

Taking the lists in the previous post in to account, lets assign ourselves a task of iterating over each element in the list and converting them to uppercase.

First, we all know how to do this in Java using a standard for each loop:

for (String s : l) { System.out.print(s.toUpperCase()); }

There are so many different ways to iterate in Scala, thus we are only going to talk about the most trivial ways.

for (s <- l) print (s.toUpperCase())

-or-

l.map(_.toUpperCase()).foreach(printf("%s", _))

Download Source: simpleLists.scala

As you can see, you can loop in Scala the same way that you do in Java, namely, with a for each loop. There is nothing special about that.

The second loop is written in more a functional paradigm, as it uses the Scala map function. It allows you to iterate over the list without having to know anything about the details of the iteration itself. With Scala you are working at a much higher level. If we look at the Scala map function, it takes in a function as an argument, in this case the function is “toUpperCase()”. The map function then applies this function to all of the elements in the List, thus you don’t have to worry about the actual iteration logic. In this scenario, all the caller needs to worry about is that they have a List of elements, and they want some function f applied to all of them.

You can chain functions together on a List. In this case, we changed a foreach to the end of the map. If we were to describe the what is going on in plain english, it would sound something like, take all the elements of l, apply “toUpperCase” to all of them, then for each of them, print them.

The final interesting thing to notice in the above line of code is the “_” placeholder syntax. It looks strange to have a “_” there as part of the code, but all it is doing is acting as a placeholder for the function. It simply represents the current element of the List being operated on. Even though there are two “_”’s in this example, they are completely independent of each other. The placeholder is a very powerful advanced concept in Scala and this example barely touches the surface of its usage. We will talk more about it in a dedicated post.

As you can see, Scala supports both the “Java” way of iterating and a pure functional way. Again, this example is just one of the many different techniques for iterating in Scala. In a future post we will look at other ways of iterating in Scala.

References

  • The code found in this post is hosted at github.com along with other sample Scala code.

This entry was posted by Steve on Sunday, November 22nd, 2009 at 2:58 pm and is filed under: , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Scala Sugar – Lists

with one comment

If I want to become a real Scala Ninja, I am going to have change the way I think about coding. For the past 10 years I have been programming primarily using the object oriented paradigm. Although Scala supports pure object oriented programming, it is my desire to learn to program in Scala in a complete functional paradigm.

Of course, learning a new programming paradigm is not going to happen over night, it is going to take a bit of time. Over the course of the next few months, I am going to be posting a series of posts documenting my progress learning Scala. They will be written from the perspective of a “hardcore” Java programmer being enlightened by a sweet new language. I will write about all of the “sugar” Scala has to offer a Java programmer, and that is how I came up with title “Scala Sugar”.

In this first installment of Scala Sugar lets discuss one of the most fundamental concepts required to write any non-trivial program, namely Lists.

For the longest time, Lists in Java didn’t bother me at all, as they seemed “normal” to me. That was until I was introduced to dynamic languages a few years back. Now, Lists in Java seem extremely verbose to me as I wonder why in Java you can’t just create and populate a list with a single line of code. Lets look at our first Java vs Scala comparison.

Lets create a trivial list of three lowercase strings.

import java.util.ArrayList;
import java.util.List;
List<String> l = new ArrayList<String>();
l.add("a");
l.add("b");
l.add("c");

In Java it takes a minimum of 6 lines of code to declare a list of 3 strings!

Now lets declare the same list in Scala.

val l = List("a", "b", "c")

Download Source: simpleLists.scala

Thats it, one line of code!

The most important things to pay attention to are:

  • No need to import List in Scala, as most fundamental classes are imported by default in Scala
  • You do not have to give ‘l’ a type in Scala. Scala uses Type inference which means that it can infer its type from the object it is pointing to. It is important to realize that Scala is statically typed, it just doesn’t require you to type your variables when you define them. The compiler is smart enough to figure it out.
  • You can construct a list with elements in Scala, no need to “add” each element separately.

Even in this trivial example, you can start to see how clean and concise Scala is.

In my next post we will explore different ways to iterate over the lists.

References

This entry was posted by Steve on Saturday, November 21st, 2009 at 4:01 pm and is filed under: , . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Fork me on GitHub Fork me on GitHub