<?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>Keep Learning &#187; Ruby</title>
	<atom:link href="http://www.makemesimple.com/blog/category/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.makemesimple.com/blog</link>
	<description>Conhecimento nunca é o bastante</description>
	<lastBuildDate>Wed, 28 Apr 2010 21:28:04 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Sentinel: agora, mais transparente do que nunca</title>
		<link>http://www.makemesimple.com/blog/2010/03/02/sentinel-agora-mais-transparente-do-que-nunca/</link>
		<comments>http://www.makemesimple.com/blog/2010/03/02/sentinel-agora-mais-transparente-do-que-nunca/#comments</comments>
		<pubDate>Tue, 02 Mar 2010 18:17:06 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Gem]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=344</guid>
		<description><![CDATA[Em Janeiro criei a gem Sentinel, que provê a funcionalidade do padrão Observer de forma transparente para código Ruby. Bom, olhando os exemplos de uso da primeira versão, é possível perceber que a biblioteca não é tão transparente assim: apesar de não alterar os métodos observados, a classe subject tem conhecimento do observer, o que [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.makemesimple.com/blog/2010/01/07/sentinel-observers-transparentes-para-seu-codigo-ruby/">Em Janeiro criei a gem Sentinel</a>, que provê a funcionalidade do padrão Observer de forma transparente para código Ruby. Bom, olhando os exemplos de uso da primeira versão, é possível perceber que a biblioteca não é tão transparente assim: apesar de não alterar os métodos observados, a classe subject tem conhecimento do observer, o que não é bom (nos comentários do post <em>linkado</em> acima falo sobre um &#8220;hack&#8221; para contornar isso, mas não é uma solução elegante).</p>
<p>Com o amadurecimento da ideia e algumas alterações no código, foi possível tornar a biblioteca totalmente transparente do ponto de vista do <em>subject</em><a href="http://github.com/lucashungaro/sentinel"> a partir da versão 0.2.0</a>. Segue um exemplo (ignore a &#8220;inocência&#8221; do código):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> User
  <span style="color:#9966CC; font-weight:bold;">def</span> save
    ...
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> UserObserver
  <span style="color:#9966CC; font-weight:bold;">include</span> Sentinel
&nbsp;
  observe User, <span style="color:#ff3333; font-weight:bold;">:save</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">notify</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">*</span>args<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#008000; font-style:italic;">#método chamado antes de user.save</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Uma atual limitação é que a interceptação é sempre feita pelo método de classe <em>notify</em> do Observer. O plano é que isso seja flexibilizado em breve.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2010/03/02/sentinel-agora-mais-transparente-do-que-nunca/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sentinel: observers transparentes para seu código Ruby</title>
		<link>http://www.makemesimple.com/blog/2010/01/07/sentinel-observers-transparentes-para-seu-codigo-ruby/</link>
		<comments>http://www.makemesimple.com/blog/2010/01/07/sentinel-observers-transparentes-para-seu-codigo-ruby/#comments</comments>
		<pubDate>Thu, 07 Jan 2010 18:46:36 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=341</guid>
		<description><![CDATA[Para uma determinada funcionalidade no Busk, precisava &#8220;trackear&#8221; todas as buscas feitas no site pelos usuários. Existem várias maneiras de conseguir esse resultado. Decidi por, de alguma forma, interceptar as chamadas ao método responsável pelas buscas (que faz o tratamento da query de busca enviada pelo usuário e chama o Sphinx). Uma das formas de [...]]]></description>
			<content:encoded><![CDATA[<p>Para uma determinada funcionalidade no <a href="http://busk.com">Busk</a>, precisava &#8220;trackear&#8221; todas as buscas feitas no site pelos usuários. Existem várias maneiras de conseguir esse resultado. Decidi por, de alguma forma, interceptar as chamadas ao método responsável pelas buscas (que faz o tratamento da query de busca enviada pelo usuário e chama o Sphinx). Uma das formas de se fazer isso é através do padrão conhecido como Observer.</p>
<p>Existem algumas bibliotecas open source que implementam Observers em Ruby e até mesmo uma na própria linguagem. Porém, queria que a implementação fosse <strong>transparente</strong>, sem alterar nada no método observado, nem mesmo adicionando uma chamada para notificar os observers, <a href="http://www.informit.com/articles/article.aspx?p=1150294&#038;seqNum=3">como é feito na implementação mais comum</a>. Daí nasceu a ideia de criar uma pequena biblioteca provendo essa funcionalidade através do recurso de aliasing do Ruby e o resultado foi batizado de <a href="http://github.com/lucashungaro/sentinel">Sentinel</a>, disponibilizado como uma gem.</p>
<p>Com essa gem, é possível interceptar chamadas a métodos de instância ou de classe através de um simples mixin (veja o Readme da gem para mais informações). De forma declarativa, definimos qual o método a ser observado e qual será o Observer notificado (qualquer objeto que responda ao método <em>notify</em>).</p>
<p>Sinta-se à vontade para sugerir modificações e notificar erros.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2010/01/07/sentinel-observers-transparentes-para-seu-codigo-ruby/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>O ActiveSupport mexeu no seu logger? Recupere a formatação original!</title>
		<link>http://www.makemesimple.com/blog/2009/09/18/o-activesupport-mexeu-no-seu-logger-recupere-a-formatacao-original/</link>
		<comments>http://www.makemesimple.com/blog/2009/09/18/o-activesupport-mexeu-no-seu-logger-recupere-a-formatacao-original/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 18:11:44 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=301</guid>
		<description><![CDATA[Recentemente estava escrevendo um script de manutenção utilizando o logger padrão do Ruby e tudo estava indo muito bem. A formatação padrão do logger oferece uma boa quantidade de informação, com timestamp, id do processo, nível da mensagem (erro, informação etc), como na imagem abaixo:
Pouco depois, resolvi utilizar o ActiveRecord (que carrega junto o ActiveSupport) [...]]]></description>
			<content:encoded><![CDATA[<p>Recentemente estava escrevendo um script de manutenção utilizando o logger padrão do Ruby e tudo estava indo muito bem. A formatação padrão do logger oferece uma boa quantidade de informação, com timestamp, id do processo, nível da mensagem (erro, informação etc), como na imagem abaixo:</p>
<div id="attachment_302" class="wp-caption aligncenter" style="width: 657px"><a href="http://www.makemesimple.com/blog/wp-content/uploads/2009/09/Picture-1.png"><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/09/Picture-1.png" alt="Formatação padrão do logger" title="default logger" width="485" height="56" class="size-full wp-image-302" /></a><p class="wp-caption-text">Formatação padrão do logger</p></div>
<p>Pouco depois, resolvi utilizar o ActiveRecord (que carrega junto o ActiveSupport) no script. Feito isso, o output do logger mudou para:</p>
<div id="attachment_303" class="wp-caption aligncenter" style="width: 405px"><a href="http://www.makemesimple.com/blog/wp-content/uploads/2009/09/Picture-2.png"><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/09/Picture-2.png" alt="Formatação com ActiveSupport" title="ActiveSupport logger output" width="315" height="41" class="size-full wp-image-303" /></a><p class="wp-caption-text">Formatação com ActiveSupport</p></div>
<p>Isso não é bom. Pesquisei um pouco e descobri que o ActiveSupport modifica a formatação padrão utilizando uma classe chamada SimpleFormatter ao invés da classe Formatter padrão do logger. </p>
<p>Desta forma, recuperar a formatação original é simples, basta modificar o formater utilizado pela sua instância do logger:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">log = <span style="color:#CC00FF; font-weight:bold;">Logger</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span>STDOUT<span style="color:#006600; font-weight:bold;">&#41;</span>
log.<span style="color:#9900CC;">datetime_format</span> = <span style="color:#996600;">&quot;%d-%m-%Y %H:%M:%S&quot;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Recuperando a formatação original</span>
log.<span style="color:#9900CC;">formatter</span> = <span style="color:#6666ff; font-weight:bold;">Logger::Formatter</span>.<span style="color:#9900CC;">new</span></pre></div></div>

<p>Também é possível alterar o formatter padrão na classe Logger. Dessa forma todas as instâncias utilizarão o formato padrão:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Fazer isso após carregar o ActiveSupport para reverter a alteração do formatter</span>
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Logger</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> formatter
    <span style="color:#0066ff; font-weight:bold;">@formatter</span> = Formatter.<span style="color:#9900CC;">new</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/09/18/o-activesupport-mexeu-no-seu-logger-recupere-a-formatacao-original/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cuidado com o DRY nos seus testes</title>
		<link>http://www.makemesimple.com/blog/2009/09/02/cuidado-com-o-dry-nos-seus-testes/</link>
		<comments>http://www.makemesimple.com/blog/2009/09/02/cuidado-com-o-dry-nos-seus-testes/#comments</comments>
		<pubDate>Wed, 02 Sep 2009 17:31:21 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Test-Driven Development]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=283</guid>
		<description><![CDATA[Don&#8217;t Repeat Yourself é um dos princípios de desenvolvimento de software mais &#8220;badalados&#8221; nos últimos tempos. O problema é que, como tudo que se torna popular, isso acaba sendo abusado. Numa tentativa de criar código limpo é comum criar código difícil de entender. Isso afeta principalmente os testes.
Testes devem ser extremamente legíveis. Não deve existir [...]]]></description>
			<content:encoded><![CDATA[<p><a target="_blank" href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself">Don&#8217;t Repeat Yourself</a> é um dos princípios de desenvolvimento de software mais &#8220;badalados&#8221; nos últimos tempos. O problema é que, como tudo que se torna popular, isso acaba sendo abusado. Numa tentativa de criar código limpo é comum criar código difícil de entender. Isso afeta principalmente os testes.</p>
<p>Testes devem ser extremamente legíveis. Não deve existir sobrecarga cognitiva, isto é, não deve ser necessário entender o código do teste para então entender o comportamento que ele especifica &#8211; isso deve ficar claro rapidamente. Exemplos de sobrecarga são a necessidade de &#8220;ficar pulando&#8221; entre vários arquivos ou &#8220;descriptografando&#8221; lógica mágica para entender o código do teste.</p>
<p>É fácil, então, identificar dois tipos de recursos que podem causar problemas no entendimento dos testes &#8211; há uma tênue linha separando o bom e o mal uso deles: macros e &#8220;magia negra&#8221; em forma de código Ruby.</p>
<p>Macros devem ser utilizadas com muito cuidado. É interessante utilizar macros que encapsulam código simples para economizar tempo na criação dos testes, como essa macro para especificar ações autenticadas com o Authlogic:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> login_as<span style="color:#006600; font-weight:bold;">&#40;</span>user<span style="color:#006600; font-weight:bold;">&#41;</span>
  activate_authlogic   <span style="color:#008000; font-style:italic;">#this is from Authlogic::TestCase</span>
  UserSession.<span style="color:#9900CC;">create</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#123;</span>:email <span style="color:#006600; font-weight:bold;">=&gt;</span> user.<span style="color:#9900CC;">email</span>, <span style="color:#ff3333; font-weight:bold;">:password</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> user.<span style="color:#9900CC;">password</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Macros com muito código ou que utilizam outras macros devem ser evitadas.</p>
<p>Um problema provavelmente mais grave é a utlização de algumas técnicas de &#8220;magia negra&#8221; no código. Aquela técnica super obscura e bacana envolvendo o Enumerable que você viu num blog esses dias não deve ser usada nos testes (nem na lógica de negócios, na minha opinião): foque sempre nos idiomas comuns da linguagem. Por simples falha da minha memória agora, segue um exemplo bobo, mas válido:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># truque menos conhecido</span>
<span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#40;</span>this is a test<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">*</span> <span style="color:#996600;">&quot;, &quot;</span>    <span style="color:#008000; font-style:italic;">#=&gt; &quot;this, is, a, test&quot;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># idioma comum</span>
<span style="color:#006600; font-weight:bold;">%</span>w<span style="color:#006600; font-weight:bold;">&#40;</span>this is a test<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;, &quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>    <span style="color:#008000; font-style:italic;">#=&gt; &quot;this, is, a, test&quot;</span></pre></div></div>

<p>Os testes, quando usados corretamente, também são a porta de entrada de novos desenvolvedores ao código já existente na aplicação. Pode ser que sua equipe seja formada por Rubistas experientes que conheçam todos os truques envolvidos, mas a adaptação de um profissional com menos experiência na linguagem pode ser muito facilitada por testes com código simples e altamente legível, mesmo que isso &#8220;custe&#8221; alguma repetição ou uso de construções mais comuns.</p>
<p>A conclusão é: em todo seu código e principalmente nos testes, evite o uso de macros que escondem muito código ou lógica relevante ao comportamento especificado e também prefira idiomas comuns, mesmo que você saiba técnicas &#8220;ninja&#8221; da linguagem.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/09/02/cuidado-com-o-dry-nos-seus-testes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Testes envolvendo tempo: usando a gem time-warp</title>
		<link>http://www.makemesimple.com/blog/2009/08/28/testes-envolvendo-tempo-usando-a-gem-time-warp/</link>
		<comments>http://www.makemesimple.com/blog/2009/08/28/testes-envolvendo-tempo-usando-a-gem-time-warp/#comments</comments>
		<pubDate>Fri, 28 Aug 2009 16:46:23 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Test-Driven Development]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=269</guid>
		<description><![CDATA[É comum que precisemos &#8220;manipular o tempo&#8221; quando escrevendo testes para código cujo comportamento depende do momento no tempo.
Uma técnica comum é utilizar um mock ou stub na classe Time do Ruby para manipular o horário de acordo com o desejado. Isso vai contra um princípio importante do uso de fake objects em testes: &#8220;Não [...]]]></description>
			<content:encoded><![CDATA[<p>É comum que precisemos &#8220;manipular o tempo&#8221; quando escrevendo testes para código cujo comportamento depende do momento no tempo.</p>
<p>Uma técnica comum é utilizar um mock ou stub na classe Time do Ruby para manipular o horário de acordo com o desejado. Isso vai contra um princípio importante do uso de fake objects em testes: &#8220;<a target="_blank" href="http://www.infoq.com/news/2008/08/Mock-Roles-Pryce-and-Freeman">Não use fakes em objetos que não são seus</a>&#8220;. Na maioria do tempo isso pode não causar problemas, mas alterar o comportamento de uma classe usada internamente pela linguagem não soa bem e pode causar bugs difíceis de rastrear.</p>
<p>Aí entra a gem <a target="_blank" href="http://github.com/iridesco/time-warp/tree/master">time-warp</a>. Ela ainda trabalha sobre as classes do Ruby, mas provê uma camada específica para testes para todo código executado em um bloco definido pelo programador. Um exemplo de uso (da <a target="_blank" href="http://twtapp.info/">nossa aplicação feita para o Rails Rumble</a>):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">it <span style="color:#996600;">&quot;should only silence tweets with the desired word inside the configured time interval&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  pretend_now_is<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">utc</span>.<span style="color:#9900CC;">beginning_of_day</span> <span style="color:#006600; font-weight:bold;">+</span> 1.<span style="color:#9900CC;">hour</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
    tweet1.<span style="color:#9900CC;">sent_at</span> = 2.<span style="color:#9900CC;">minutes</span>.<span style="color:#9900CC;">ago</span>
    tweet2.<span style="color:#9900CC;">sent_at</span> = 32.<span style="color:#9900CC;">minutes</span>.<span style="color:#9900CC;">from_now</span>
    tweet3.<span style="color:#9900CC;">sent_at</span> = 1.<span style="color:#9900CC;">hour</span>.<span style="color:#9900CC;">from_now</span>
&nbsp;
    collection = <span style="color:#006600; font-weight:bold;">&#91;</span>tweet1, tweet2, tweet3<span style="color:#006600; font-weight:bold;">&#93;</span>
&nbsp;
    Silencer.<span style="color:#9900CC;">apply</span><span style="color:#006600; font-weight:bold;">&#40;</span>collection, <span style="color:#006600; font-weight:bold;">&#123;</span>:word <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;soccer&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:until</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> 30.<span style="color:#9900CC;">minutes</span>.<span style="color:#9900CC;">from_now</span><span style="color:#006600; font-weight:bold;">&#125;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  tweet1.<span style="color:#9900CC;">should</span> be_filtered
  tweet2.<span style="color:#9900CC;">should</span> be_filtered
  tweet3.<span style="color:#9900CC;">should_not</span> be_filtered
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>A gem adiciona o método &#8220;pretend_now_is&#8221;, que recebe um parâmetro com o horário desejado e um bloco. Dentro desse bloco, todo código executado é &#8220;transportado no tempo&#8221; para o horário definido. Além de tornar a manipulação das classes de tempo mais segura, o código fica muito mais elegante.</p>
<p>Veja mais detalhes no <a target="_blank" href="http://github.com/iridesco/time-warp/blob/884623fec90687c7f3c28b8e8074a39c96946cbb/README.md">README da gem</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/08/28/testes-envolvendo-tempo-usando-a-gem-time-warp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Obtendo informações de uma instalação do Ruby</title>
		<link>http://www.makemesimple.com/blog/2009/05/03/obtendo-informacoes-de-uma-instalacao-do-ruby/</link>
		<comments>http://www.makemesimple.com/blog/2009/05/03/obtendo-informacoes-de-uma-instalacao-do-ruby/#comments</comments>
		<pubDate>Sun, 03 May 2009 04:09:16 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=196</guid>
		<description><![CDATA[Existem algumas maneiras de obter informações sobre uma instalação do Ruby, mas uma que conheci hoje é através do próprio irb, utilizando uma biblioteca chamada rbconfig, presente na instalação padrão do Ruby.
Para iniciar o irb já com essa lib carregada, basta executar o comando: irb -r rbconfig (a flag -r diz ao irb para carregar [...]]]></description>
			<content:encoded><![CDATA[<p>Existem algumas maneiras de obter informações sobre uma instalação do Ruby, mas uma que conheci hoje é através do próprio <code>irb</code>, utilizando uma biblioteca chamada <code>rbconfig</code>, presente na instalação padrão do Ruby.</p>
<p>Para iniciar o irb já com essa lib carregada, basta executar o comando: <code>irb -r rbconfig</code> (a flag -r diz ao irb para carregar uma lib ao iniciar). Para obter algumas configurações da instalação Ruby, acesse o hash <code>Config::CONFIG</code>. Veja alguns exemplos (clique para ver a imagem maior):</p>
<p><a href="http://www.makemesimple.com/blog/wp-content/uploads/2009/05/ishot-1.jpg" target="_blank"><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/05/ishot-1.jpg" alt="irb with rbconfig" title="irb with rbconfig" width="478" height="248" class="aligncenter size-medium" /></a></p>
<p><strong>Nota</strong>: em algumas instalações, essa biblioteca já é carregada com o <code>irb</code> por padrão.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/05/03/obtendo-informacoes-de-uma-instalacao-do-ruby/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Evitando over-stubbing com Mocha</title>
		<link>http://www.makemesimple.com/blog/2009/03/18/evitando-over-stubbing-com-mocha/</link>
		<comments>http://www.makemesimple.com/blog/2009/03/18/evitando-over-stubbing-com-mocha/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 16:45:29 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Anúncios]]></category>
		<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Test-Driven Development]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=191</guid>
		<description><![CDATA[Não é segredo que não sou &#8220;fã&#8221; da maneira como a comunidade de desenvolvedores utiliza mocks e stubs. A meu ver, trata-se de mal uso de uma ferramenta muito útil.
Com esse tipo de uso surgem alguns problemas, tais como over-mocking e over-stubbing, ou seja, o uso abusivo de mocks e stubs. O abuso de mocks [...]]]></description>
			<content:encoded><![CDATA[<p>Não é segredo que não sou &#8220;fã&#8221; da maneira como a comunidade de desenvolvedores utiliza mocks e stubs. A meu ver, trata-se de mal uso de uma ferramenta muito útil.</p>
<p>Com esse tipo de uso surgem alguns problemas, tais como over-mocking e over-stubbing, ou seja, o uso abusivo de mocks e stubs. O abuso de mocks torna seus testes quebradiços, isto é, testes que falham sem que haja alteração de comportamento do componente sob verificação. O abuso de stubs torna seus testes fracos, isto é, testes que saem de sincronia com o código, verificando comportamento que já não é real, mas continuam passando.</p>
<p>Um exemplo de abuso de mocks:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">it <span style="color:#996600;">&quot;should be successful&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  Account.<span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:new</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">with</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:current_user</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@user</span>, <span style="color:#ff3333; font-weight:bold;">:first_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Test&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:last_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;Test&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">returns</span><span style="color:#006600; font-weight:bold;">&#40;</span>@account<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#0066ff; font-weight:bold;">@account</span>.<span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:login_method</span>=<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">with</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">CONFIG::LOGIN::OpenID</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#0066ff; font-weight:bold;">@account</span>.<span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:has_email_and_password</span>=<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">at_least_once</span>
  <span style="color:#0066ff; font-weight:bold;">@account</span>.<span style="color:#9900CC;">expects</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:has_openid</span>=<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">twice</span>
  do_edit
  response.<span style="color:#9900CC;">should</span> be_success
  response.<span style="color:#9900CC;">should</span> render_template<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;edit&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Note que até métodos de atribuição são colocados sob expectativas. Se a implementação sofrer uma alteração simples, fazendo, por exemplo, com que algum desses métodos não seja mais chamado, mesmo que não haja qualquer modificação no comportamento, o teste falhará.</p>
<p>Um exemplo do abuso de stubs:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">it <span style="color:#996600;">&quot;has been modified a lot of times&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  Dependency.<span style="color:#9900CC;">stubs</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:a_method</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  NoLongerADependency.<span style="color:#9900CC;">stubs</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:something</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">returns</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">false</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  AnotherDependency.<span style="color:#9900CC;">stubs</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:nonexistent_method</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">returns</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">10</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  MyClass.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">do_something</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Com esse tipo de abordagem, você pode acabar com problemas como fazer stubs de métodos que não existem mais ou até mesmo de objetos que já não são mais uma dependência.</p>
<p>Uma forma de evitar isso com o Mocha (além, é claro, de estudar o uso correto das ferramentas) é utilizar algumas configurações providas pelo framework através de sua classe Configuration:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">prevent</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:stubbing_non_existent_method</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#impede stubbing de métodos inexistentes</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">prevent</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:stubbing_method_unnecessarily</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#impede stubbing de métodos não utilizados</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">prevent</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:stubbing_non_public_method</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#impede stubbing de métodos não-públicos</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">prevent</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:stubbing_method_on_non_mock_object</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;">#impede stubbing em objetos &quot;reais&quot;</span></pre></div></div>

<p>Nos exemplos acima, caso encontre um dos usos &#8220;indevidos&#8221;, o Mocha lançará uma exceção do tipo Mocha::StubbingError. Isso ocorre por termos utilizado o método prevent. Há outras configurações possíveis, sendo providos três nívels de configuração:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># padrão - permite a condição</span>
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">allow</span><span style="color:#006600; font-weight:bold;">&#40;</span>condition<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># apenas emite um aviso quando ocorre a condição</span>
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">warn_when</span><span style="color:#006600; font-weight:bold;">&#40;</span>condition<span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># lança um erro quando ocorre a condição</span>
<span style="color:#6666ff; font-weight:bold;">Mocha::Configuration</span>.<span style="color:#9900CC;">prevent</span><span style="color:#006600; font-weight:bold;">&#40;</span>condition<span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Essas configurações podem ser um auxílio para o aprendizado do uso correto e equilibrado da ferramenta.</p>
<p>Leia mais:<br />
<a href="http://mocha.rubyforge.org/classes/Mocha/Configuration.html" target="_blank">Mocha::Configuration RDoc</a><br />
<a href="http://blog.floehopper.org/articles/2009/02/09/mocha-configuration" target="_blank">Mocha Configuration &#8211; James Mead</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/03/18/evitando-over-stubbing-com-mocha/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Ruby Quick Tip: Aprendendo através de testes</title>
		<link>http://www.makemesimple.com/blog/2009/02/08/ruby-quick-tip-aprendendo-atraves-de-testes/</link>
		<comments>http://www.makemesimple.com/blog/2009/02/08/ruby-quick-tip-aprendendo-atraves-de-testes/#comments</comments>
		<pubDate>Sun, 08 Feb 2009 21:07:09 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=156</guid>
		<description><![CDATA[Se você não conhece (completamente ou pacialmente) alguma biblioteca, uma boa forma de fazer isso é através de um caso de testes. 
Um benefício resultante dessa prática é poder executar os testes contra várias versões do Ruby e, assim, verificar alterações em sua estrutura.
Se você usa o TextMate, é muito fácil criar um caso de [...]]]></description>
			<content:encoded><![CDATA[<p>Se você não conhece (completamente ou pacialmente) alguma biblioteca, uma boa forma de fazer isso é através de um caso de testes. </p>
<p>Um benefício resultante dessa prática é poder executar os testes contra várias versões do Ruby e, assim, verificar alterações em sua estrutura.</p>
<p>Se você usa o TextMate, é muito fácil criar um caso de testes. Basta abrir uma janela do editor, ativar o bundle do Ruby, digitar <em>tc</em> e pressionar a tecla <em>tab</em>:</p>
<p><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/02/ishot-1.jpg" alt="TextMate" title="TextMate" width="475" height="449" class="aligncenter size-full wp-image-161" /></p>
<p><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/02/ishot-2.jpg" alt="test case scaffold" title="test case scaffold" width="475" height="449" class="aligncenter size-full wp-image-162" /></p>
<p>Com isso temos um &#8220;esqueleto&#8221; de um caso de testes pronto. Pressionando tab, o foco do cursor passa por pontos importantes, como o require da biblioteca a ser testada, o nome do caso de testes etc. Agora, basta modificar de acordo com o que queremos testar e, através do atalho command+R, executar os testes e verificar o resultado:</p>
<p><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/02/ishot-3.jpg" alt="test" title="test" width="475" height="449" class="aligncenter size-full wp-image-163" /></p>
<p><img src="http://www.makemesimple.com/blog/wp-content/uploads/2009/02/ishot-41.jpg" alt="ishot-41" title="ishot-41" width="500" height="331" class="aligncenter size-full wp-image-174" /></p>
<p><strong>Veja também</strong>:</p>
<p><a href="http://www.makemesimple.com/blog/2007/08/27/aprendizado-orientado-por-testes/">Aprendizado orientado por testes</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2009/02/08/ruby-quick-tip-aprendendo-atraves-de-testes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby quick tip: Blocos para fallback em hash lookups</title>
		<link>http://www.makemesimple.com/blog/2008/07/13/ruby-quick-tip-blocos-para-fallback-em-hash-lookups/</link>
		<comments>http://www.makemesimple.com/blog/2008/07/13/ruby-quick-tip-blocos-para-fallback-em-hash-lookups/#comments</comments>
		<pubDate>Mon, 14 Jul 2008 01:50:35 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=134</guid>
		<description><![CDATA[Normalmente, ao tentar fazer um lookup em um hash com uma chave não existente, você tem o seguinte comportamento:

&#62;&#62; h = &#123;:foo =&#62; &#34;bar&#34;&#125;
=&#62; &#123;:foo=&#62;&#34;bar&#34;&#125;
&#62;&#62; h&#91;:other_foo&#93;
=&#62; nil

Você pode adicionar um bloco para tratar esses casos:

&#62;&#62; h = Hash.new &#123; &#124;hash, key&#124; &#34;#{key} is not here&#34;&#125;
=&#62; &#123;&#125;
&#62;&#62; h&#91;:foo&#93;
=&#62; &#34;foo is not here&#34;

É possível, inclusive, alterar o [...]]]></description>
			<content:encoded><![CDATA[<p>Normalmente, ao tentar fazer um lookup em um hash com uma chave não existente, você tem o seguinte comportamento:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h = <span style="color:#006600; font-weight:bold;">&#123;</span>:foo <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;bar&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span>:foo<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#996600;">&quot;bar&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:other_foo</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">nil</span></pre></div></div>

<p>Você pode adicionar um bloco para tratar esses casos:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h = <span style="color:#CC00FF; font-weight:bold;">Hash</span>.<span style="color:#9900CC;">new</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>hash, key<span style="color:#006600; font-weight:bold;">|</span> <span style="color:#996600;">&quot;#{key} is not here&quot;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:foo</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;foo is not here&quot;</span></pre></div></div>

<p>É possível, inclusive, alterar o hash em questão:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h = <span style="color:#CC00FF; font-weight:bold;">Hash</span>.<span style="color:#9900CC;">new</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>hash, key<span style="color:#006600; font-weight:bold;">|</span> hash<span style="color:#006600; font-weight:bold;">&#91;</span>key<span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;value for #{key}&quot;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006600; font-weight:bold;">&#123;</span><span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#006600; font-weight:bold;">&gt;&gt;</span> h<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:foo</span><span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;value for foo&quot;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2008/07/13/ruby-quick-tip-blocos-para-fallback-em-hash-lookups/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>21 truques de Ruby que você deveria estar usando</title>
		<link>http://www.makemesimple.com/blog/2008/05/28/21-truques-de-ruby-que-voce-deveria-estar-usando/</link>
		<comments>http://www.makemesimple.com/blog/2008/05/28/21-truques-de-ruby-que-voce-deveria-estar-usando/#comments</comments>
		<pubDate>Wed, 28 May 2008 13:59:32 +0000</pubDate>
		<dc:creator>Lucas Húngaro</dc:creator>
				<category><![CDATA[Dicas]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.makemesimple.com/blog/?p=129</guid>
		<description><![CDATA[Creio que a maioria já viu o artigo 21 Ruby Tricks You Should Be Using In Your Own Code no Ruby Inside. O texto contém truques realmente interessantes, mas esse post é apenas para uma dica: se você ainda não assina o feed do Ruby Inside, faça-o agora!  
]]></description>
			<content:encoded><![CDATA[<p>Creio que a maioria já viu o artigo <a href="http://www.rubyinside.com/21-ruby-tricks-902.html" target="_blank">21 Ruby Tricks You Should Be Using In Your Own Code</a> no <a href="http://www.rubyinside.com/" target="_blank">Ruby Inside</a>. O texto contém truques realmente interessantes, mas esse post é apenas para uma dica: se você ainda não assina o feed do Ruby Inside, <a href="http://www.rubyinside.com/feed" target="_blank">faça-o agora</a>! <img src='http://www.makemesimple.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.makemesimple.com/blog/2008/05/28/21-truques-de-ruby-que-voce-deveria-estar-usando/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.664 seconds -->
