Creating Windows With Ruby Tk

The Ruby language supports creating windows for GUI (Graphic User Interface). GUI applications are programs that respond to user input, which are usually mouse events, such as clicking buttons, clicking menus, etc.

A GUI application may consist of the following types of objects:

  • Widgets – basic GUI objects that can be put directly in the window. Most of them generate events as a response to user actions. A label is a widget, too, but, usually does not generate events.
  • Shapes – lines, arcs, circles, polygons and other that belong on a canvas.
  • Timers – threads that perform an action the number of times specified and sleep for theĀ  specified duration. From the definition “thread” you can understand that they run in parallel.

The simplest Ruby Tk program is:


require 'tk'
Tk.mainloop

This program displays the following window:

This is the default window. It is displayed on the screen when the line ‘Tk.mainloop’ is performed. Until this window is closed, no commands that are not responses to events will be executed.

“Programing Ruby – The Pragmatic Programmers Guide” suggests that you look at Perl/Tk guides to learn how to use Tk. A good place to look for Perl’s objects and their methods is Active Perl. I’m not going to write here the complete guide to Ruby Tk, but I hope the following chapters will help you understand how it works.

To be continued.

Advertisement

JSON, The New XML

When you write for the web, you may want to send data to another server or to a client. A common way to transfer that data is in XML format. The data will then be processed using SAX, DOM or XPath. Every language support it.

If what you want is to define a variable, an object or an array in Javascript, you can use the JSON extension. JSON is an acronym for ‘Java Script Object Notation’. In Javascript you can use it as follows:

var myObject=<?php echo json_encode($php_object); >;

Here no parsers are required.

Here’s an example of using it in PHP:

<?
class my_class {
  public $prop1;
  public $prop2;

  function __construct(){
    $this->prop1='a';
    $this->prop2=400;
  }
}

$obj=new my_class();
echo json_encode($obj);
?>

The output looks like:
{“prop1″:”a”,”prop2″:400}

In addition to encoding, a JSON string can be decoded into an object in a language other than Javascript. Thus, you can pass data in the JSON format to any program supporting JSON, and, as you can see in www.json.org, most languages used today support it.

The ability to encode varibles into JSON and decode it back in any language is not the only reason why JSON can replace XML. If you go to www.json.org, you can see links in the bottom referring to other sites. For example, JSONPath, that allows you to access a member just like XPath. JSONPath is available in PHP and Javascript.