Tuesday, October 2, 2007

poor man's dashboard

Just when I thought I'd found all the simple stuff in ruby, I found %x.

I needed to display the tail of a log file. Thoughts of opening the file, pushing each line into a fixed length array, popping the last line off, etc filled my head. Duh - just shell out and do a tail.

Here's the one-liner as it appears in a view. It also re-sorts to display latest first:

<p><%= %x(tail -n 30 log/activity_log.log).split('\n').reverse.join('<br/>') %></p>

%x shells out to the os and returns stdout (if any) in a string.

2 comments:

rtaljun said...

The method doesn't return stdout, it returns a String, although it will print to stdout as a side-effect.

You can also use the Kernel.system() method, or my personal favorite, just put it in backticks (`ls` for example).

The last one is particularly useful because you can escape code inside of it, for example `cd #{dirname}`

p.latyp.us said...

rtaljun, nice correction - thanks! Good tip on the back ticks, too! Jim.