<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>RuGUI Framework Blog &#187; Tutorials</title>
	<atom:link href="http://blog.rugui.org/tag/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.rugui.org</link>
	<description>RuGUI is an open-source framework that makes building desktop applications very easy. Like Ruby on Rails, it aims to improve productivity, favoring convention over configuration, DRY and MVC patterns.</description>
	<lastBuildDate>Fri, 25 Sep 2009 16:06:07 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>OlÃ¡ RuGUI! Desenvolvendo aplicaÃ§Ãµes desktop utilizando Ruby/GTK</title>
		<link>http://blog.rugui.org/2009/02/ola-rugui/</link>
		<comments>http://blog.rugui.org/2009/02/ola-rugui/#comments</comments>
		<pubDate>Tue, 03 Feb 2009 01:18:04 +0000</pubDate>
		<dc:creator>Vicente Mundim</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[gtk]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[RuGUI]]></category>

		<guid isPermaLink="false">http://blog.intelitiva.com/?p=10</guid>
		<description><![CDATA[Este post Ã© a traduÃ§Ã£o do post intitulado Hello RuGUI!

EntÃ£o vocÃª quer comeÃ§ar a brincar com GTK e Ruby mas ainda nÃ£o sabe por onde comeÃ§ar? NÃ£o tenha medo, estamos aqui para ajudÃ¡-lo. Existem muitos exemplos de programas &#8220;OlÃ¡, Mundo!&#8221; com Ruby/GTK. Bem, ambos Ruby e GTK sÃ£o excelentes escolhas para a construÃ§Ã£o de aplicaÃ§Ãµes [...]]]></description>
			<content:encoded><![CDATA[<p>Este post Ã© a traduÃ§Ã£o do post intitulado <a href="http://blog.rugui.org/2009/01/hello-rugui/">Hello RuGUI!</a></p>
<p><a title="RuGUI Framework" href="http://rugui.org"><img src="http://blog.rugui.org/wp-content/uploads/2009/01/logo_rugui.png" alt="RuGUI" /></a></p>
<p>EntÃ£o vocÃª quer comeÃ§ar a brincar com GTK e Ruby mas ainda nÃ£o sabe por onde comeÃ§ar? NÃ£o tenha medo, estamos aqui para ajudÃ¡-lo. Existem muitos exemplos de programas &#8220;OlÃ¡, Mundo!&#8221; com Ruby/GTK. Bem, ambos Ruby e GTK sÃ£o excelentes escolhas para a construÃ§Ã£o de aplicaÃ§Ãµes desktop. Ruby Ã© uma linguagem dinÃ¢mica com caracterÃ­sticas incrÃ­veis como closures e, Ã© claro, uma extensa biblioteca prÃ³pria. GTK, por sua vez, Ã© um framework amplamente utilizado, com muitas widgets Ãºteis alÃ©m de ter uma API Ã³tima para impressÃ£o, exibiÃ§Ã£o de vÃ­deos, reproduÃ§Ã£o de Ã¡udio, etc. Combine esses dois elementos e vocÃª chega ao Ruby/GTK, um Ã³timo framework&#8230; uhmmm&#8230; framework?</p>
<p>Deixe-me perguntar algumas questÃµes para vocÃª. Suponha que vocÃª esteja comeÃ§ando a escrever uma nova aplicaÃ§Ã£o desktop em Ruby/GTK, uma que seja realmente grande, com muitos casos de uso e pequenos detalhes. Como vocÃª desenharia sua estrutura de diretÃ³rios? E se vocÃª quisesse personalizar o estilo de um botÃ£o, ou alterar a cor de fundo de um TextView? E se sua aplicaÃ§Ã£o fosse um tipo de servidor, e vocÃª quisesse exibir uma mensagem toda vez que um usuÃ¡rio se conectasse? E se vocÃª quisesse alterar a mensagem na barra de status, alÃ©m de adicionar um Ã­cone para o cliente numa IconView?</p>
<p>Ã‰ claro que tudo isso poderia ser feito manualmente por vocÃª&#8230; Ou vocÃª poderia utilizar o <a href="http://rugui.org">RuGUI</a>, que lhe oferece:</p>
<ul>
<li>Uma abordagem MVC para aplicaÃ§Ãµes desktop</li>
<li>Uma estrutura de diretÃ³rios, pronta para uso, similar ao que se tem em aplicaÃ§Ãµes <a href="http://rubyonrails.org">Ruby on Rails</a></li>
<li>Uma maneira mais fÃ¡cil de personalizar widgets do que em aplicaÃ§Ãµes Ruby/GTK normais</li>
<li>ActiveSupport &#8211; bem, alguÃ©m poderia dizer que isso Ã© um requerimento/dependÃªncia, mas eu penso nisso mais como uma funcionalidade extra, uma vez que vocÃª acaba tendo uma API ruby muito mais rica e Ãºtil com ActiveSupport <img src='http://blog.rugui.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<p>Vejamos ele em aÃ§Ã£o com um simples &#8220;Hello, World&#8221;:</p>
<h3>Gerando o esqueleto da sua aplicaÃ§Ã£o</h3>
<p>O  <strong>RuGUI</strong> jÃ¡ cria essa aplicaÃ§Ã£o Hello World para nÃ³s. Na verdade este Ã© o ponto de partida de cada aplicaÃ§Ã£o que vocÃª virÃ¡ a fazer com o <strong>RuGUI</strong>. Uma vez instalado com uma gem vÃ¡ para um diretÃ³rio de sua escolha e digite num terminal:</p>
<pre>  rugui helloworld</pre>
<p>Isso irÃ¡ gerar uma aplicaÃ§Ã£o em {SEU_DIRETORIO}/helloworld.  A estrutura de diretÃ³rios serÃ¡ assim:</p>
<p><img src="http://blog.rugui.org/wp-content/uploads/2009/02/pastas_pt.png" alt="Estrutura de DiretÃ³rios de uma AplicaÃ§Ã£o RuGUI" width="585" height="440" class="size-full wp-image-16" /></p>
<p>Para rodar a aplicaÃ§Ã£o, entre no diretÃ³rio helloworld e digite:</p>
<pre>  ./bin/helloworld</pre>
<p>VocÃª poderia ter digitado tambÃ©m:</p>
<pre>  rake run</pre>
<p>Ou, se vocÃª precisar:</p>
<pre>  ruby app/main.rb</pre>
<p>A aplicaÃ§Ã£o deve ser similar a isso:</p>
<p><img src="http://blog.rugui.org/wp-content/uploads/2009/01/helloworld.png" alt="Hello, World!" /></p>
<p>Se vocÃª clicar no botÃ£o, verÃ¡ o texto acima sendo alterado. Como tudo isso funcionou?</p>
<h3>Hello world passo a passo</h3>
<p>Vamos analisar a aplicaÃ§Ã£o passo a passo:</p>
<p>Quando vocÃª roda a aplicaÃ§Ã£o, de qualquer forma (todas as trÃªs formas de iniciar a aplicaÃ§Ã£o acabam por fazer a mesma coisa), o script app/main.rb Ã© chamado. Aqui estÃ¡ o conteÃºdo desse arquivo:</p>
<pre class="brush: ruby;">
#! /usr/bin/ruby

# You can run this application by running this file.
# Do not modify it, unless you know what you are doing.

require File.join(File.dirname(__FILE__), '..', 'config', 'environment')

main_controller = MainController.new
main_controller.run
</pre>
<p>Como vocÃª pode ver, a primeira coisa que fazemos Ã© carregar o arquivo config/environment.rb. Isto irÃ¡ inicializar a aplicaÃ§Ã£o *RuGUI* com o ambiente padrÃ£o &#8212; development. VocÃª poderia ter especificado um ambiente diferente configurando a variÃ¡vel de ambiente RUGUI_ENV. Esse procedimento de inicializaÃ§Ã£o Ã© muito similar ao procedimento de inicializaÃ§Ã£o do Rails, ele foi basicamente copiado e adaptado.</p>
<p>Em seguida nÃ³s instanciamos o <code>MainController</code> e chamamos o mÃ©todo <code>run</code>. Simples, nÃ£o?</p>
<p>Agora sobre o <code>MainController</code>. O quÃª que ele Ã© mesmo? Ao contrÃ¡rio de aplicaÃ§Ãµes web, todas as aplicaÃ§Ãµes desktop possuem um conceito de loop principal. Basicamente, a aplicaÃ§Ã£o Ã© toda configurada antes de ser exibida. Ela entÃ£o entra num loop infinito, que Ã© responsÃ¡vel por exibir as widgets, disparar eventos conforme vÃ£o acontecendo (cliques em botÃµes, apertos de teclas, trÃ¡fego de rede, operaÃ§Ãµes de impressÃ£o, etc). Esses eventos podem alterar a aparÃªncia de widgets, os dados exibidos, ou qualquer outra coisa que vocÃª queira que seja feito.</p>
<p>EntÃ£o o <code>MainController</code> do <strong>RuGUI</strong> Ã© o ponto de partida real da programaÃ§Ã£o de sua aplicaÃ§Ã£o. Algo como a raiz de sua aplicaÃ§Ã£o. Melhor ainda, todos os controles sÃ£o filhos desse <code>MainController</code>, ou filhos de controles que sÃ£o filhos do <code>MainController</code>. Isso estÃ¡ ficando complicado, mas com o tempo vocÃª irÃ¡ entender.</p>
<p>Neste exemplo, nÃ³s temos apenas um controle, e ele Ã© o <code>MainController</code>. NÃ£o criamos outro controle por simplicidade. Aqui estÃ¡ seu cÃ³digo:</p>
<pre class="brush: ruby;">
class MainController &lt; RuGUI::BaseMainController
  # Add your stuff here.

  def setup_views
    register_view :main_view
  end

  def on_main_window_delete_event(widget, event)
    quit
  end
end
</pre>
<p>Ele configura a view principal e adiciona um manipulador para o evento em que a janela principal Ã© fechada, que Ã© usado para fechar a aplicaÃ§Ã£o. Este manipulador de eventos Ã© configurado no arquivo main_view.glade. Todo controle pode observar eventos configurados por widgets em arquivos glade de todas as views registradas nele.</p>
<p>A view principal utiliza um arquivo glade para simplificar a criaÃ§Ã£o e o posicionamento de widgets. NÃ³s poderÃ­amos ter criado as widgets manualmente, mas teriÃ¡mos perdido muitas das funcionalidades como a conexÃ£o automÃ¡tica de manipuladores de eventos, alÃ©m de ter de escrever muito mais cÃ³digo do que foi escrito:</p>
<pre class="brush: ruby;">
class MainView &lt; ApplicationView
  use_glade
  # Add your stuff here.

  def on_hello_button_clicked(widget)
    puts &quot;Hello button clicked.&quot;
    self.message_label.text = &quot;You clicked me!&quot;
  end
end
</pre>
<p>Aqui nÃ³s colocamos um manipulador de evento para o clique do botÃ£o hello_button. Ele imprime uma mensagem no console, e altera o texto da widget message_label. Algumas notas aqui:</p>
<ul>
<li>Todas as widgets criadas em arquivos glade possuem acessores de leitura para elas</li>
<li>Uma vez que estamos utilizando a nomeclatura e a estrutura de diretÃ³rios padrÃ£o nÃ£o tivemos que especificar o arquivo glade para a view, mas poderÃ­amos fazÃª-lo se quisÃ©ssemos. Ele foi meramente deduzido a partir do nome da classe (MainView =&gt; main_view).</li>
<li>A view tambÃ©m funciona como um observador para manipuladores de eventos de suas widgets. O manipulador do evento de clique de botÃ£o para o hello_button poderia ter sido declaro no controle, mas nÃ³s decidimos declarÃ¡-lo aqui para mostrar isso.</li>
</ul>
<p>Isso Ã© basicamente tudo o que hÃ¡!</p>
<h3>Mas, peraÃ­, eu consigo fazer isso em menos linhas!</h3>
<p>Ã‰ claro que sim, aqui estÃ¡:</p>
<pre class="brush: ruby;">
#! /usr/bin/ruby

require 'libglade2'

class MainViewGlade
  include GetText
  attr :glade

  def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
    bindtextdomain(domain, localedir, nil, &quot;UTF-8&quot;)
    @glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}
  end

  def on_main_window_delete_event(widget, arg0)
    Gtk.main_quit
  end

  def on_hello_button_clicked(widget)
    puts &quot;Hello button clicked.&quot;
    @glade['message_label'].text = &quot;You clicked me!&quot;
  end
end

# Main program
if __FILE__ == $0
  # Set values as your own application.
  PROG_PATH = &quot;main_view.glade&quot;
  PROG_NAME = &quot;Hello World!&quot;
  MainViewGlade.new(PROG_PATH, nil, PROG_NAME)
  Gtk.main
end
</pre>
<p>No entanto, vocÃª muito provavelmente terÃ¡ uma grande dor de cabeÃ§a quando precisar adicionar mais funcionalidades Ã  aplicaÃ§Ã£o. <strong>RuGUI</strong> procura te ajudar ao deixar vocÃª separar a sua aplicaÃ§Ã£o em camadas bem definidas, cada uma com suas responsabilidades. Dessa forma fica muito mais fÃ¡cil fazer com que sua aplicaÃ§Ã£o evolua sem problemas na sua manutenÃ§Ã£o.</p>
<p>EstÃ¡ ficando animado? <a title="Getting started with RuGUI" href="http://rugui.org/GettingStarted">Comece</a> a usÃ¡-lo agora mesmo!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rugui.org/2009/02/ola-rugui/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Hello RuGUI! Developing desktop applications using Ruby/GTK</title>
		<link>http://blog.rugui.org/2009/01/hello-rugui/</link>
		<comments>http://blog.rugui.org/2009/01/hello-rugui/#comments</comments>
		<pubDate>Wed, 28 Jan 2009 22:50:21 +0000</pubDate>
		<dc:creator>Vicente Mundim</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[gtk]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[RuGUI]]></category>

		<guid isPermaLink="false">http://blog.intelitiva.com/?p=5</guid>
		<description><![CDATA[Introduce basic concepts needed to start out with RuGUI framework.]]></description>
			<content:encoded><![CDATA[<p>You can check out a portuguese version of this post <a href="http://blog.rugui.org/2009/02/ola-rugui/">here</a></p>
<p><a href="http://rugui.org" title="RuGUI Framework"><img src="http://blog.rugui.org/wp-content/uploads/2009/01/logo_rugui.png" alt="RuGUI" /></a></p>
<p>So you want to start out playing with GTK and Ruby but donâ€™t know how to start? Fear not, weâ€™re here to help you. There are a lot of examples of â€œHello, World!â€ applications with Ruby/GTK. Well, both Ruby and GTK are great choices for building desktop applications. The first one is a dynamic language with amazing features like closures, and of course, with an extensive built-in library. The second one is a widely used GUI framework, with lots of helpful widgets and also a great library for printing, displaying videos, playing sounds, etc. Combine these two elements and you have Ruby/GTK, a great frameworkâ€¦ uhmmmâ€¦ framework?</p>
<p>Let me ask you a few questions. Suppose youâ€™re starting a new desktop application in Ruby/GTK, a really big one, with lots of use cases and small details. How would you layout your directory structure? What if you needed to customize the style of a button, or change the background color of a TextView? What if your application is a kind of server, and you want some message displayed every time an user connects to it? What if you wanted to change the status bar message, and also add an icon for the client in an IconView?</p>
<p>Of course you could do this yourselfâ€¦ Or you could use <a href="http://rugui.org" title="RuGUI Framework"><strong>RuGUI</strong></a> which gives you:</p>
<ul>
<li>A MVC approach to desktop applications</li>
<li>A ready to use directory layout similar to what youâ€™d see on a <a href="http://rubyonrails.org/">Ruby on Rails</a> application</li>
<li>An easier way of customizing widgets than in normal Ruby/GTK applications</li>
<li>An implementation of the Observer pattern</li>
<li>ActiveSupportâ€”hey, you could say that this is a requirement/dependency, but I think this is more like a feature since you&#8217;ll end up having a better ruby API with ActiveSupport <img src='http://blog.rugui.org/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </li>
</ul>
<p>Letâ€™s see it in action with a simple Hello World application.</p>
<h3>Generating your application skeleton</h3>
<p><strong>RuGUI</strong> already creates this Hello World application for us. In fact this is the starting point for every application youâ€™ll ever make with <strong>RuGUI</strong>. Once it is installed as a gem go to a directory of your choice and type in a terminal:</p>
<pre>rugui helloworld</pre>
<p>This will generate an application in {YOUR_DIRECTORY}/helloworld. The directory structure will be like this:</p>
<p><img src="http://blog.rugui.org/wp-content/uploads/2009/02/pastas_en.png" alt="pastas_en" width="570" height="440" class="alignleft size-full wp-image-18" /></p>
<p>To run the application, enter the helloworld directory and type:</p>
<pre>./bin/helloworld</pre>
<p>You could also have typed:</p>
<pre>rake run</pre>
<p>Or even, if you must:</p>
<pre>ruby app/main.rb</pre>
<p>The application should look like this:</p>
<p><img src="http://blog.rugui.org/wp-content/uploads/2009/01/helloworld.png" alt="Hello World Application" /></p>
<p>If you click in the button you should see the top label changing. How did this all worked?</p>
<h3>Hello World step by step</h3>
<p>Letâ€™s analyse the application step by step:</p>
<p>When you run the application, in any way (all three ways of starting the application end up doing the same thing), the app/main.rb script gets called. Here are the content of that file:</p>
<pre class="brush: ruby;">
#! /usr/bin/ruby#

# You can run this application by running this file.
# Do not modify it, unless you know what you are doing.

require File.join(File.dirname(__FILE__), '..', 'config', 'environment')

main_controller = MainController.new
main_controller.run
</pre>
<p>As you can see, the first thing we do is to load the config/environment.rb file. This will initialize the <strong>RuGUI</strong> application with the default environmentâ€”development. You couldâ€™ve specified a different environment by setting the RUGUI_ENV environment variable. This initialization process is very similar to the Rails initialization process, it was mainly copied and adapted from it.</p>
<p>Next we instantiate the <code>MainController</code> and call its method <code>run</code>. Simple isnâ€™t?</p>
<p>Now to the MainController. What is it again? Unlike web applications, all desktop applications have a concept of a main loop. Basically, the application is set up before it is actually displayed. It then enters an infinite loop, which is responsible for displaying widgets and firing events as they happen (button clicks, keys pressed, network data, printing operations, etc). These events may alter the widgets visual, change data, or any other thing you might want them to do.</p>
<p>So <strong>RuGUI</strong>â€™s MainController is the actual programming starting point of your application. Something like the root of your application. Better yet, all other controllers are children of this MainController, or children of controllers which are themselves children of this MainController. This is getting a little complicated, but in time you will get it.</p>
<p>In this example we only have one controller, and it is the MainController. We didnâ€™t create another controller for simplicity. Here is its code:</p>
<pre class="brush: ruby;">
class MainController &lt; RuGUI::BaseMainController
  # Add your stuff here.

Â  def setup_views
Â    register_view :main_view
Â  end

  def on_main_window_delete_event(widget, event)
Â    quit
Â  end
end
</pre>
<p>It set up the main view and add a handler for the main window delete event, which is used to quit the application. This event handler is configured in the main_view.glade file. Every controller can observe events configured for widgets in glade files of all views registered for it.</p>
<p>The main view uses glade file to simplify the creation an positioning of widgets. We couldâ€™ve created the widgets by hand, but we wouldâ€™ve lost many features like the automatic connection of event handlers, and we would have to write a lot more code than we did:</p>
<pre class="brush: ruby;">
class MainView &lt; ApplicationView
Â  use_glade
  # Add your stuff here.

  def on_hello_button_clicked(widget)
Â    puts &quot;Hello button clicked.&quot;
Â    self.message_label.text = &quot;You clicked me!&quot;
Â  end
end
</pre>
<p>Here weâ€™ve put an event handler for the clicked event of the hello_button widget. It prints a message in the console and change the text of the message_label widget. A few notes here:</p>
<ul>
<li>All named widgets created in glade files have read accessors for them.</li>
<li>Since we are using default naming and directory conventions we didnâ€™t need to specify the builder file for the view, but we could have done it if we wanted. It was merely deducted from the class name (MainView =&gt; main_view)</li>
<li>The view itself is also an observer for event handlers of its widgets. The clicked event handler for the hello_button could have been declared in the controller, but weâ€™ve decided to declare it here to show this.</li>
</ul>
<p>This is basically all there is to it!</p>
<h3>But hey, I can do this with fewer lines!</h3>
<p>Of course you can, here it is:</p>
<pre class="brush: ruby;">
#! /usr/bin/ruby

require 'libglade2'

class MainViewGlade
  include GetText
  attr :glade

  def initialize(path_or_data, root = nil, domain = nil, localedir = nil, flag = GladeXML::FILE)
Â    bindtextdomain(domain, localedir, nil, &quot;UTF-8&quot;)
Â    @glade = GladeXML.new(path_or_data, root, domain, localedir, flag) {|handler| method(handler)}
Â  end

  def on_main_window_delete_event(widget, arg0)
Â    Gtk.main_quit
Â  end

  def on_hello_button_clicked(widget)
Â    puts &quot;Hello button clicked.&quot;
Â    @glade['message_label'].text = &quot;You clicked me!&quot;
Â  end
end

# Main program
if __FILE__ == $0
Â  # Set values as your own application.
Â  PROG_PATH = &quot;main_view.glade&quot;
Â  PROG_NAME = &quot;Hello World!&quot;
Â  MainViewGlade.new(PROG_PATH, nil, PROG_NAME)
Â  Gtk.main
end
</pre>
<p>But then, you will surely get a big headache when you need to add more functionality to the application. <strong>RuGUI</strong> tries to help you by letting you separate your application in well defined layers, each with his own responsabilities. This way its easier to make your application evolve without having maintainence problems.</p>
<p>Getting excited? <a href="http://rugui.org/GettingStarted" title="Getting started with RuGUI">Try</a> it out now!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rugui.org/2009/01/hello-rugui/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
