Friday, September 17, 2010

Ruby magic variables

Playing in irb console a little bit and I found interesting behaviour:
irb(main):001:0> defined? x
=> nil
irb(main):002:0> x
NameError: undefined local variable or method `x' for main:Object
        from (irb):2
irb(main):003:0> x = 1 if false
=> nil
irb(main):004:0> defined? x
=> "local-variable"
irb(main):005:0> x
=> nil
Looks like ruby allocates memory for all variables, even when the block was not executed.

With this knownledge we can simlify our if / while statements.
So, as an example, we can change this:
irb(main):012:0> if false == true
irb(main):013:1> z = "not possible"
irb(main):014:1> else
irb(main):015:1* z = nil
irb(main):016:1> end
=> nil
irb(main):017:0> print "Output: #{z}"
into this:
irb(main):019:0> if false == true
irb(main):020:1> z = "not possible"
irb(main):021:1> end
=> nil
irb(main):022:0> print "Output: #{z}"
Output: => nil
As you see z variable was allocated (and set to default nil) and we don't need to initialize it "one more time".

Happy refactoring :)

Thursday, September 16, 2010

Ruby/Mac/Growl: SVN new revision notifier


I would like to show you really nice and helpful notification script.
I use it to notify me of new SVN revision, but it can be easily modified and use in some different way.

Here come the script:
#!/usr/bin/env ruby     

while true do
  tmp = `svn st -u | grep '*' | cut -c 21-`
  tmp2 = tmp.split("\n")
  tmp3 = `pwd`
  tmp3 = tmp3.split('/').last
  tmp3.gsub!("\n", "")

  if tmp2.size > 0
    message = "'#{tmp.gsub("\n", " ")}' #{tmp2.size.to_s} new files in #{tmp3}"
    system "growlnotify -n check_svn -m #{message} --image ./worms.png"
    puts message
  end

  puts Time.now.strftime('%Y-%m-%d %H:%M:%S')
  sleep(60)
end

So, how it works?
Every 60 seconds we run svn up -u command and if there's something new in repository, we print a list of new files using growlnotify (from Growl package - http://growl.info).
That's all :)

The console output:

... and worm icon: