SpicyCode

The ramblings of Chad Humphries

Posts Tagged ‘console

console apps here i come?

I’ve been meaning to talk about simpleconsole for a while now. After seeing tofuu post about it on his blog recently it’s got me thinking about writing a few simple apps in ruby for the command line.

You get some really wicked fun options when writing console apps (as seen in the code below from tofuu’s post).

#!/usr/bin/env ruby -w
require "rubygems" 
require "simpleconsole" 

class Controller < SimpleConsole::Controller
  params :string => {:n => :name}
  before_filter :check_params, :only => [:hello] # you might see a face instead of "only" 

  def hello
    @name = params[:name]
  end

private
  def check_params
    if invalid_params?
      puts "Invalid option(s) - " + invalid_params.join(", ")
    end
  end
end

class View < SimpleConsole::Controller
  def help
    puts "Usage: myapp [action] [--options]" 
  end

  def hello
    puts "Hi, " + @name + "."     # <-- Thanks to Brandon Z for catching that
  end
end

SimpleConsole::Application.run(ARGV, Controller, View)

Which gives you….

% myapp help
Usage: myapp [action] [--options]
% myapp hello --invalid
Invalid option(s) - invalid
% myapp hello -n Hugh
Hi, Hugh.
% myapp hello --name MyName
Hi, MyName.

I think it will be a fun change of pace to work outside of rails for a while.

Written by spicycode

November 6, 2006 at 6:40 pm

Posted in programming

Tagged with ,