<?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>1up4developers &#187; rails</title>
	<atom:link href="http://1up4dev.org/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://1up4dev.org</link>
	<description>Nadando contra o Waterfall. tail -f /mind/realworld &#62;&#62; /blog</description>
	<lastBuildDate>Tue, 08 Nov 2011 11:00:28 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Dica Rápida: Removendo o test unit de um projeto Rails 3</title>
		<link>http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/</link>
		<comments>http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 11:00:28 +0000</pubDate>
		<dc:creator>Roger Leite</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=1114</guid>
		<description><![CDATA[TweetEste post serve mais como &#8220;cola&#8221; de referência, pois toda vez que vou fazer isso eu não encontro fácil no google e nunca lembro. Por sinal é mega simples, é só editar o config/application.rb e remover a linha: require 'rails/all' E substituir por: &#8230; <a href="http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/" data-text="Dica Rápida: Removendo o test unit de um projeto Rails 3" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Este post serve mais como &#8220;cola&#8221; de referência, pois toda vez que vou fazer isso eu não encontro fácil no google e nunca lembro. Por sinal é mega simples, é só editar o <em>config/application.rb</em> e remover a linha:</p>
<pre>require 'rails/all'</pre>
<p>E substituir por:</p>
<pre>require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"</pre>
<p>Após isso, já não aparece mais as tasks de testes, e você pode remover a pasta test.</p>
<pre>$ git rm -r test/</pre>
<p>Pra finalizar, já segue a dica de alterar a task <em>default</em>, no final do <em>Rakefile</em> é só colocar:</p>
<pre>Rake::Task[:default].prerequisites.clear
task :default =&gt; :spec  #no caso do rspec</pre>
<p>Sucesso!</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/11/dica-rapida-removendo-o-test-unit-de-um-projeto-rails-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CoffeeScript quem?</title>
		<link>http://1up4dev.org/2011/04/coffescript-what/</link>
		<comments>http://1up4dev.org/2011/04/coffescript-what/#comments</comments>
		<pubDate>Thu, 14 Apr 2011 13:20:26 +0000</pubDate>
		<dc:creator>Plínio Balduino</dc:creator>
				<category><![CDATA[novidades da semana]]></category>
		<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[coffee script]]></category>
		<category><![CDATA[coffeescript]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=934</guid>
		<description><![CDATA[TweetMuito buzz se formou depois que o DHH tornou público que a versão 3.1 do Rails virá com CofeeScript por padrão. Aproveitando a barulheira, que é comum a cada vez que o criador da plataforma abre a boca, vamos nos &#8230; <a href="http://1up4dev.org/2011/04/coffescript-what/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/04/coffescript-what/" data-text="CoffeeScript quem?" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/04/coffescript-what/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Muito buzz se formou depois que o DHH tornou público que a versão 3.1 do Rails virá com CofeeScript por padrão.</p>
<p>Aproveitando a barulheira, que é comum a cada vez que o criador da plataforma abre a boca, vamos nos ater ao que é importante e apresentar uma introdução ao resumo simplificado do CoffeeScript básico.</p>
<p>Confesso que minha opinião sobre essa ferramenta mudou nos primeiros instantes em que comecei a usar. No site do CoffeeScript (ok se eu começar a chamar de CS daqui para frente?) existe um link onde você digita o código do lado esquerdo e, imediatamente, do lado direito aparece o equivalente em JavaScript.</p>
<p>Fiz uma brincadeira lá usando um código que sempre me vem à cabeça ao tentar explicar o básico de programação funcional para alguem. Segue:</p>
<pre>mimimi = (operation, value) ->
   operation(value);

dobro = (value) ->
  value + value;

quadrado = (value) ->
  value * value;

zero = (value) ->
  value - value;

um = (value) ->
  value / value;

alert(mimimi(dobro, 3));
alert(mimimi(quadrado, 3));
alert(mimimi(zero, 3));
alert(mimimi(um, 3));</pre>
<p>Nada de outro mundo, certo? O equivalente JS é o código abaixo:</p>
<pre>var dobro, mimimi, quadrado, um, zero;
mimimi = function(operation, value) {
  return operation(value);
};
dobro = function(value) {
  return value + value;
};
quadrado = function(value) {
  return value * value;
};
zero = function(value) {
  return value - value;
};
um = function(value) {
  return value / value;
};
alert(mimimi(dobro, 3));
alert(mimimi(quadrado, 3));
alert(mimimi(zero, 3));
alert(mimimi(um, 3));</pre>
<p>CS permite também a checagem automática de valores e parâmetros opcionais, conforme o exemplo retirado do site:</p>
<pre>fill = (container, liquid = "coffee") -&gt;
  "Filling the #{container} with #{liquid}..."</pre>
<p>Ou o equivalente em JS:</p>
<pre>var fill;
fill = function(container, liquid) {
  if (liquid == null) {
    liquid = "coffee";
  }
  return "Filling the " + container + " with " + liquid + "...";
};</pre>
<p>Sem dúvida, muito mais legível e expressivo.</p>
<p>É uma ferramenta que eu pretendo usar em algum projeto pequeno, para testar e ver o quanto acelera meu trabalho. Em projetos maiores talvez eu demore um pouco mais para usar mas, considerando que umas das minhas aplicações já conta com 79% de código total escrito em JavaScript, segundo o GitHub, imagino que isso vai melhorar consideravelmente a manutenção do código.</p>
<p>E no mais, se o CS não te chamou a atenção e você não quer mesmo utilizar, basta remover o require do arquivo Gemfiles e a vida segue como se nada tivesse acontecido.</p>
<p>Links recomendados:</p>
<ul>
<li>Site do CoffeScript: <a title="http://jashkenas.github.com/coffee-script/" href="http://jashkenas.github.com/coffee-script/" target="_blank">http://jashkenas.github.com/coffee-script/</a></li>
<li>Mais do mesmo: <a title="http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html" href="http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html" target="_blank">http://www.rubyinside.com/rails-3-1-adopts-coffeescript-jquery-sass-and-controversy-4669.html</a></li>
<li>Exemplo bacana de como utilizar CS dentro da sua view: <a title="http://geekiriki.blogspot.com/2010/08/jquery-meets-coffeescript.html" href="http://geekiriki.blogspot.com/2010/08/jquery-meets-coffeescript.html" target="_blank">http://geekiriki.blogspot.com/2010/08/jquery-meets-coffeescript.html</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/04/coffescript-what/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Documentação não pode ser chato. Como fazer igual ao Rails Guides !</title>
		<link>http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/</link>
		<comments>http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/#comments</comments>
		<pubDate>Thu, 24 Feb 2011 03:52:40 +0000</pubDate>
		<dc:creator>Roger Leite</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[real world]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[documentação]]></category>
		<category><![CDATA[rails guides]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=878</guid>
		<description><![CDATA[TweetDocumentação é aquilo que você reclama para fazer e reclama quando não encontra. Por Plínio &#8220;Chico Xavier&#8221; via Twitter. Isto me fez refletir (bem rápido) sobre as possíveis causas da não-documentação: É muito chato ! Editar wiki, doc &#8230; é incrível &#8230; <a href="http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/" data-text="Documentação não pode ser chato. Como fazer igual ao Rails Guides !" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><blockquote><p>Documentação é aquilo que você reclama para fazer e reclama quando não encontra.</p></blockquote>
<p>Por <a href="http://1up4dev.org/author/pbalduino/">Plínio</a> &#8220;Chico Xavier&#8221; via <a href="http://twitter.com/#!/p_balduino/status/35689585455407105">Twitter</a>.</p>
<p>Isto me fez refletir (bem rápido) sobre as possíveis causas da não-documentação:</p>
<ul>
<li>É muito chato ! Editar wiki, doc &#8230; é incrível como toda documentação geralmente é feita em algo não produtivo.</li>
<li>Espaço e Tempo (ou seja, prazo!). Sempre é deixado por último e nunca sobra tempo pra ser feito.</li>
<li>Não é levado a sério. Levanta a mão que já viu a secretária documentando &#8220;tela&#8221; de sistema &#8230; <img src='http://1up4dev.org/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> </li>
<li>Normalmente o &#8220;investidor&#8221; do software não vê valor nisto, ou melhor, espera alguém pedir e repassa a tarefa com prioridade &#8220;faz rapidinho&#8221;.</li>
</ul>
<p>Ok. Após reflexão feita, hora de atacar o problema.</p>
<h2>Usando &#8220;guides&#8221; para criar um Guide !</h2>
<p>Este é um resultado da experiência abaixo:</p>
<p style="text-align: center;"><a href="http://rogerleite.github.com/rubygems_snapshot/"><img class="aligncenter size-medium wp-image-891" title="Snapshot Guide (inspirado no Rails Guides)" src="http://1up4dev.org/wp-content/uploads/2011/02/snapshot_guide-300x241.png" alt="Snapshot Guide (inspirado no Rails Guides)" width="300" height="241" /></a></p>
<p>Com a gem <a href="https://github.com/wycats/guides">guides</a>, em segundos você tem um <em>scaffold</em>, pronto para ser preenchido.</p>
<pre><span style="font-family: Georgia, 'Bitstream Charter', serif; color: #444444;"><span style="line-height: 22px;">$ gem install guides</span></span></pre>
<pre><span style="font-family: Georgia, 'Bitstream Charter', serif; color: #444444;"><span style="line-height: 22px;"> </span></span><span style="color: #444444; font-family: Georgia, 'Bitstream Charter', serif; line-height: 22px;">$ guides #mostra os comandos disponíveis</span></pre>
<pre><span style="font-family: Georgia, 'Bitstream Charter', serif; color: #444444;"><span style="line-height: 22px;">$ guides new sample</span></span></pre>
<pre><span style="font-family: Georgia, 'Bitstream Charter', serif; color: #444444;"><span style="line-height: 22px;">$ cd sample</span></span></pre>
<pre><span style="font-family: Georgia, 'Bitstream Charter', serif; color: #444444;"><span style="line-height: 22px;">$ guides build &amp;&amp; guides preview</span></span></pre>
<p>Pronto. Em http://localhost:9292 você terá acesso ao novo guia gerado.</p>
<h3>Preenchendo o seu Guia</h3>
<p>Em <em>guides.yml</em> (exemplo <a href="https://github.com/rogerleite/rubygems_snapshot/blob/master/guides/guides.yml">aqui</a>), está o básico do seu Guia. Nele está o índice de &#8220;capítulos&#8221;, com resumo e nome do arquivo que o link deve seguir. Os arquivos textile  gerados/criados ficarão na pasta <em>source</em>, o resultado do &#8220;guides build&#8221; ficará na pasta <em>output</em>.</p>
<p>As páginas são em <a href="http://www.textism.com/tools/textile/">textile</a>, o que facilita bastante. Mas o grande diferencial, está em alguns <em>helpers</em> disponibilizados pela gem, que torna muito simples criar áreas de destaque como INFO, WARNING &#8230; etc e adicionar comandos e códigos.</p>
<p>Para ter idéia de uma página em textile, segue o link <a href="https://github.com/rogerleite/rubygems_snapshot/raw/master/guides/source/getting_started.textile">source/getting_started.textile</a> (raw).</p>
<h3>Repensando a documentação</h3>
<p>Com certeza, usando a <em>gem guides</em>, vocẽ consegue um boost na hora de documentar. Já evitando aquela chatice de editar wiki, .doc, controlando versão &#8230; etc. Usando textile, seu editor preferido e git, não tem mais desculpas.</p>
<h4>Desenvolvendo Frameworks e APIs</h4>
<p>Já faz um tempo que eu topo com a <em>vibe</em> <a href="http://www.google.com.br/search?sourceid=chrome&amp;ie=UTF-8&amp;q=Documentation+Driven+Development">Documentation Driven Development</a>. Como tudo na vida, é questão de bom senso. Documentar uma API, nada mais é do que definir a interface dela, e dependendo do caso, isto ajuda bastante antes de começar o desenvolvimento.</p>
<h4>Você é um Usuário !</h4>
<p>Uma documentação com um monte de imagem e seta, descrevendo o óbvio não serve para nada (além de passar raiva). Uma documentação <strong>sucinta</strong>, com o básico, por exemplo Instalação, Modo de Usar, Configurações Disponíveis é bem melhor que muito dossiê por aí ! Tente ao máximo se colocar no lugar do usuário ao escrever alguma documentação ou ajuda.</p>
<p>&#8212;</p>
<p>Não deixe de contribuir com o post. Mande sugestões, comentários, reclamações etc.</p>
<p><span style="line-height: 24px; font-size: 16px;"> </span></p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/02/documentacao-nao-pode-ser-chato-como-fazer-igual-ao-rails-guides/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Resenha do livro Crafting Rails Applications</title>
		<link>http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/</link>
		<comments>http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/#comments</comments>
		<pubDate>Wed, 02 Feb 2011 12:05:53 +0000</pubDate>
		<dc:creator>Roger Leite</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[real world]]></category>
		<category><![CDATA[resenhas]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[resenha]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=841</guid>
		<description><![CDATA[TweetNo final do ano passado, ao ver um twitty do José Valim, fiquei tentando a comprar o livro, mas depois do post Crafting Rails Applications: Why I wrote this book, tive certeza que não perderia este presente de Natal. Apesar &#8230; <a href="http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/" data-text="Resenha do livro Crafting Rails Applications" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>No final do ano passado, ao ver um <a href="http://twitter.com/josevalim/status/12537904249176064">twitty do José Valim</a>, fiquei tentando a comprar o livro, mas depois do post <a href="http://blog.plataformatec.com.br/2010/12/crafting-rails-applications-why-i-wrote-this-book/">Crafting Rails Applications: Why I wrote this book</a>, tive certeza que não perderia este presente de Natal.</p>
<div id="attachment_847" class="wp-caption alignleft" style="width: 200px"><a href="http://pragprog.com/titles/jvrails/crafting-rails-applications"><img class="size-full wp-image-847" title="Crafting Rails Applications: Expert Practices for Everyday Rails Development" src="http://1up4dev.org/wp-content/uploads/2011/02/jvrails.jpg" alt="Crafting Rails Applications: Expert Practices for Everyday Rails Development" width="190" height="228" /></a><p class="wp-caption-text">Crafting Rails Applications: Expert Practices for Everyday Rails Development</p></div>
<p>Apesar de poucas páginas, o livro tem muito conteúdo. Logo no começo, em &#8220;<em>Who should read this book ?</em>&#8221; é avisado, <strong>não é para iniciantes</strong>. Os capítulos são separados em tópicos interessantes, abordando diferentes maneiras de extender o Rails 3.</p>
<p>Aliás, extender é a palavra chave do livro. Dos projetos que compõe o Rails, somente o <em>Active Resource</em> não foi citado. O livro com certeza pula o básico, ou seja, não espere por explicações em como usar as funcionalidades do Rails.</p>
<p>-</p>
<h2>Detalhes que tornam o livro interessante.</h2>
<ul>
<li><a href="https://github.com/josevalim/enginex">Enginex</a> &#8211; é uma Ruby gem que cria um <em>Rails 3 Engine</em> com Rakefile, Gemfile e pronto para rodar testes em cima de uma aplicação &#8220;vendorizada&#8221;. Ou seja, no livro temos projetos reais, que são executados e tem testes !</li>
<li><a href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a> &#8211; todo código apresentado, é feito seguindo o <em>Test-driven Development</em>, mostra-se o teste falhando e vai implementando aos poucos, até tudo ficar verde.</li>
<li><span style="text-decoration: underline;">Como melhorar o seu código</span> &#8211; conhecendo <em>Responders</em> e o <em>Renderer Stack do Rails 3</em>, você com certeza irá ampliar o seu leque de possibilidades de como melhorar o fonte das suas aplicações. Tem bastante exemplos de <em>Rails Generators</em> também.</li>
<li><span style="text-decoration: underline;">Desmistificando Rails</span> &#8211; o Valim realmente conseguiu de forma majestosa explicar as entranhas do Rails 3. A cada capítulo e detalhe explicado, pude ver o verdadeiro trampo que fizeram no projeto, em comparação com o 2.x, o Rails mudou muito (internamente!).</li>
</ul>
<h2>Finalizando&#8230;</h2>
<p>Se você é um desenvolvedor que se preocupa em conhecer a fundo o framework que trabalha, <strong><a href="http://pragprog.com/titles/jvrails/crafting-rails-applications">compre agora</a></strong>! Confesso que depois da leitura, estou muito mais a vontade para navegar no fontes do Rails, inclusive passei a acompanhar os tickets no <a href="https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Lighthouse</a>. <img src='http://1up4dev.org/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' />  <a href="https://github.com/rails/rails">Rails 3</a> definitivamente está mais flexível, e o José Valim conseguiu expor tudo isso com código e uma leitura agradável.</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/02/resenha-do-livro-crafting-rails-applications/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Deploy de várias aplicações no Nginx + Passenger usando subdomain ou suburi</title>
		<link>http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/</link>
		<comments>http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/#comments</comments>
		<pubDate>Wed, 26 Jan 2011 10:00:59 +0000</pubDate>
		<dc:creator>Rodrigo Panachi</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=770</guid>
		<description><![CDATA[TweetSe você está pensando em fazer o deploy da sua aplicação Rails em um server Nginx com Phusion Passenger, você está no caminho certo! Não apenas pela segurança e performance do Nginx, mas também pela facilidade de instalação e configuração &#8230; <a href="http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/" data-text="Deploy de várias aplicações no Nginx + Passenger usando subdomain ou suburi" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Se você está pensando em fazer o deploy da sua aplicação Rails em um server <a href="http://nginx.org/">Nginx</a> com <a href="http://www.modrails.com/">Phusion Passenger</a>, você está no caminho certo! Não apenas pela segurança e performance do Nginx, mas também pela facilidade de instalação e configuração quando comparado à outros web servers populares. </p>
<p>A <a href="http://wiki.nginx.org/Install">instalação do Nginx</a> bem como <a href="http://www.modrails.com/install.html">configuração do módulo do Passenger</a> são relativamente simples. A documentação de <a href="http://www.modrails.com/documentation/Users%20guide%20Nginx.html#_installing_phusion_passenger">ambos é bem completa</a>. Você provavelmente não terá muita dificuldade. Eu recomendo seguir o passo-a-passo da instalação do Passenger:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;">  passenger-install-nginx-module</pre></div></div>

<p>Uma vez que tudo esteja instalado, é hora de configurar o Nginx editando o arquivo <code>nginx.conf</code> (provavelmente localizado em <code>/usr/local/nginx/conf/nginx.conf</code>)</p>
<h3>Usando sub URI</h3>
<p>O deploy como sub URI torna sua aplicação acessível com o endereço <code>http://dominio.com/app1</code>, sendo <code>app1</code> o nome da sua aplicação. Supondo que diretório público do Nginx esteja em <code>/var/www</code> e sua aplicação Rails em <code>/var/rails/app1</code>, configure-o assim:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">http <span style="color:#006600; font-weight:bold;">&#123;</span>
    ...
    <span style="color:#9900CC;">server</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
        listen <span style="color:#006666;">80</span>;
        server_name dominio.<span style="color:#9900CC;">com</span> www.<span style="color:#9900CC;">dominio</span>.<span style="color:#9900CC;">com</span>;
        root <span style="color:#006600; font-weight:bold;">/</span>var<span style="color:#006600; font-weight:bold;">/</span>www;
        passenger_enabled on;
        passenger_base_uri <span style="color:#006600; font-weight:bold;">/</span>app1;
    <span style="color:#006600; font-weight:bold;">&#125;</span>
    ...
<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>Ainda é preciso criar um link simbólico para que o contexto da aplicação Rails seja visível pelo document root em <code>/var/www</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ln</span> <span style="color: #660033;">-s</span> <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>rails<span style="color: #000000; font-weight: bold;">/</span>app1<span style="color: #000000; font-weight: bold;">/</span>public <span style="color: #000000; font-weight: bold;">/</span>var<span style="color: #000000; font-weight: bold;">/</span>www<span style="color: #000000; font-weight: bold;">/</span>app1</pre></div></div>

<p>Reiniciando o Nginx, sua aplicação já estará rodando. Para adicionar outras aplicações, basta adicionar:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">        passenger_base_uri <span style="color:#006600; font-weight:bold;">/</span>app1;
        passenger_base_uri <span style="color:#006600; font-weight:bold;">/</span>app2;
        passenger_base_uri <span style="color:#006600; font-weight:bold;">/</span>app3;</pre></div></div>

<p>E em seguida criar os links simbólicos como descrito acima. Nota importante: em alguns casos, será necessário informar a URL relativa correta nas configurações do Rails:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">   config.<span style="color:#9900CC;">action_controller</span>.<span style="color:#9900CC;">relative_url_root</span> = <span style="color:#996600;">&quot;/app1&quot;</span></pre></div></div>

<h3>Usando subdomain</h3>
<p>O deploy como subdomain torna sua aplicação acessível com o endereço <code>http://app1.dominio.com</code>. Basta configurar o Nginx como segue:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">http <span style="color:#006600; font-weight:bold;">&#123;</span>
    ...
    <span style="color:#9900CC;">server</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
        listen <span style="color:#006666;">80</span>;
        server_name app1.<span style="color:#9900CC;">dominio</span>.<span style="color:#9900CC;">com</span>;
        root <span style="color:#006600; font-weight:bold;">/</span>var<span style="color:#006600; font-weight:bold;">/</span>rails<span style="color:#006600; font-weight:bold;">/</span>app1<span style="color:#006600; font-weight:bold;">/</span>public;
        passenger_enabled on;
    <span style="color:#006600; font-weight:bold;">&#125;</span>
    ...
<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>Note que o <code>root</code> aponta diretamente para o diretório &#8220;public&#8221; da aplicação Rails. Para fazer o deploy de outras aplicações como subdomínio, basta configurar outro &#8220;server&#8221;, alterando <code>root</code> e o <code>server_name</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">http <span style="color:#006600; font-weight:bold;">&#123;</span>
    ...
    <span style="color:#9900CC;">server</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
        listen <span style="color:#006666;">80</span>;
        server_name app1.<span style="color:#9900CC;">dominio</span>.<span style="color:#9900CC;">com</span>;
        root <span style="color:#006600; font-weight:bold;">/</span>var<span style="color:#006600; font-weight:bold;">/</span>rails<span style="color:#006600; font-weight:bold;">/</span>app1<span style="color:#006600; font-weight:bold;">/</span>public;
        passenger_enabled on;
    <span style="color:#006600; font-weight:bold;">&#125;</span>
    ...
    <span style="color:#9900CC;">server</span> <span style="color:#006600; font-weight:bold;">&#123;</span>
        listen <span style="color:#006666;">80</span>;
        server_name app2.<span style="color:#9900CC;">dominio</span>.<span style="color:#9900CC;">com</span>;
        root <span style="color:#006600; font-weight:bold;">/</span>var<span style="color:#006600; font-weight:bold;">/</span>rails<span style="color:#006600; font-weight:bold;">/</span>app2<span style="color:#006600; font-weight:bold;">/</span>public;
        passenger_enabled on;
    <span style="color:#006600; font-weight:bold;">&#125;</span>
    ...
<span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>Uma vez que o DNS do host esteja corretamente configurado, suas aplicações estarão acessíveis em <code>http://app1.dominio.com</code>, <code>http://app2.dominio.com</code>, etc.</p>
<p>Dúvidas ou sugestões, utilizem os comentários. Sucesso!</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/01/deploy-de-varias-aplicacoes-no-nginx-passenger-usando-subdomain-ou-suburi/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Enviando emails no Rails através do Gmail</title>
		<link>http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/</link>
		<comments>http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 09:00:09 +0000</pubDate>
		<dc:creator>Rodrigo Panachi</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=774</guid>
		<description><![CDATA[TweetEnviar emails de uma aplicação Rails é muito simples. A parte complicada fica com a configuração do ambiente e do servidor de email. Se você não souber ou não tiver muita paciência para fazer isso (por exemplo instalar e configurar &#8230; <a href="http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/" data-text="Enviando emails no Rails através do Gmail" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Enviar emails de uma aplicação Rails é <a href="http://guides.rubyonrails.org/action_mailer_basics.html">muito simples</a>. A parte complicada fica com a configuração do ambiente e do servidor de email. Se você não souber ou não tiver muita paciência para fazer isso (por exemplo instalar e configurar <a href="http://www.sendmail.org">sendmail</a>, <a href="http://www.mutt.org/">mutt</a>, etc), pode facilmente usar sua conta do <a href="http://lindsaar.net/2010/3/15/how_to_use_mail_and_actionmailer_3_with_gmail_smtp">Gmail</a> para enviar as mensagens da sua aplicação.</p>
<p>Basta incluir as seguintes configurações no bloco <code>config</code> dos respectivos ambientes da aplicação (por exemplo, <code>config/environments/production.rb</code>):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">  config.<span style="color:#9900CC;">action_mailer</span>.<span style="color:#9900CC;">delivery_method</span> = <span style="color:#ff3333; font-weight:bold;">:smtp</span>
  config.<span style="color:#9900CC;">action_mailer</span>.<span style="color:#9900CC;">smtp_settings</span> = <span style="color:#006600; font-weight:bold;">&#123;</span>
    <span style="color:#ff3333; font-weight:bold;">:enable_starttls_auto</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">true</span>,
    <span style="color:#ff3333; font-weight:bold;">:authentication</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#ff3333; font-weight:bold;">:plain</span>,
    <span style="color:#ff3333; font-weight:bold;">:address</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> smtp.<span style="color:#9900CC;">gmail</span>.<span style="color:#9900CC;">com</span>,
    <span style="color:#ff3333; font-weight:bold;">:port</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#006666;">587</span>,
    <span style="color:#ff3333; font-weight:bold;">:user_name</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;seuemail@gmail.com&quot;</span>,
    <span style="color:#ff3333; font-weight:bold;">:password</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;suasenha&quot;</span>
  <span style="color:#006600; font-weight:bold;">&#125;</span></pre></div></div>

<p>O toque mágico é a chave <code>:enable_startls_auto =&gt; true</code> para habilitar <a href="http://en.wikipedia.org/wiki/Transport_Layer_Security">TLS</a>. Sucesso!</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/01/enviando-emails-no-rails-atraves-do-gmail/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Usando Bundler com Rails 2.3</title>
		<link>http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/</link>
		<comments>http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/#comments</comments>
		<pubDate>Mon, 17 Jan 2011 11:00:55 +0000</pubDate>
		<dc:creator>Plínio Balduino</dc:creator>
				<category><![CDATA[rails]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=745</guid>
		<description><![CDATA[TweetIniciando minha participação neste blog, vou apresentar uma solução rápida para um problema que eu tive e levei um certo tempo para encontrar uma resposta. Caso você não conheça, Bundler é uma ferramenta criada para facilitar a instalação e atualização &#8230; <a href="http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/" data-text="Usando Bundler com Rails 2.3" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Iniciando minha participação neste blog, vou apresentar uma solução rápida para um problema que eu tive e levei um certo tempo para encontrar uma resposta.</p>
<p>Caso você não conheça, Bundler é uma ferramenta criada para facilitar a instalação e atualização de aplicações e suas gems, resolvendo facilmente as dependências e criando ambientes homogêneos em máquinas diferentes. Em outras palavras, resolve de uma vez por todas aquele inferno que era ter que baixar gem por gem da sua aplicação e ainda assim correr o risco de encontrar alguma incompatibilidade.</p>
<p>O Rails 3 utiliza o Bundler por padrão, mas aplicações em Rails 2.x ainda dependem das gems declaradas no arquivo <code>config/environment.rb</code>, e ao copiar os arquivos para uma determinada máquina, você é obrigado a usar <code>rake gems:install</code>, que vai levar algum tempo rodando e não vai instalar tudo o que você precisa.</p>
<p>Ou pelo menos era assim que funcionava até você ler esse post.</p>
<p>Primeiro, considerando que você esteja no diretório raiz da sua aplicação, execute a sequência abaixo:</p>
<p>Antes de qualquer outra coisa, instale o Bundler na sua máquina executando o comando <code>gem install bundler</code></p>
<p>No seu arquivo <code>config/boot.rb</code>, imediatamente antes da linha <code>Rails.boot!</code>, insira o bloco abaixo:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#6666ff; font-weight:bold;">Rails::Boot</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> run
    load_initializer
&nbsp;
    <span style="color:#6666ff; font-weight:bold;">Rails::Initializer</span>.<span style="color:#9900CC;">class_eval</span> <span style="color:#9966CC; font-weight:bold;">do</span>
      <span style="color:#9966CC; font-weight:bold;">def</span> load_gems
        <span style="color:#0066ff; font-weight:bold;">@bundler_loaded</span> <span style="color:#006600; font-weight:bold;">||</span>= Bundler.<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#ff3333; font-weight:bold;">:default</span>, Rails.<span style="color:#9900CC;">env</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    <span style="color:#6666ff; font-weight:bold;">Rails::Initializer</span>.<span style="color:#9900CC;">run</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:set_load_path</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Crie um arquivo <code>config/preinitializer.rb</code>. Esse arquivo não existe no Rails 2.x, então se você não criar, não vai funcionar. Adicione as linhas abaixo nesse arquivo:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">begin</span>
  <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;rubygems&quot;</span>
  <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">&quot;bundler&quot;</span>
<span style="color:#9966CC; font-weight:bold;">rescue</span> <span style="color:#CC00FF; font-weight:bold;">LoadError</span>
  <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#996600;">&quot;Could not load the bundler gem. Install it with `gem install bundler`.&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#6666ff; font-weight:bold;">Gem::Version</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">Bundler::VERSION</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&lt;</span>= <span style="color:#6666ff; font-weight:bold;">Gem::Version</span>.<span style="color:#9900CC;">new</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;0.9.24&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#CC00FF; font-weight:bold;">RuntimeError</span>, <span style="color:#996600;">&quot;Your bundler version is too old for Rails 2.3.&quot;</span> <span style="color:#006600; font-weight:bold;">+</span>
   <span style="color:#996600;">&quot;Run `gem install bundler` to upgrade.&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">begin</span>
  <span style="color:#008000; font-style:italic;"># Set up load paths for all bundled gems</span>
  ENV<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;BUNDLE_GEMFILE&quot;</span><span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">expand_path</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;../../Gemfile&quot;</span>, <span style="color:#0000FF; font-weight:bold;">__FILE__</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  Bundler.<span style="color:#9900CC;">setup</span>
<span style="color:#9966CC; font-weight:bold;">rescue</span> <span style="color:#6666ff; font-weight:bold;">Bundler::GemNotFound</span>
  <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#CC00FF; font-weight:bold;">RuntimeError</span>, <span style="color:#996600;">&quot;Bundler couldn't find some gems.&quot;</span> <span style="color:#006600; font-weight:bold;">+</span>
    <span style="color:#996600;">&quot;Did you run `bundle install`?&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Crie um arquivo chamado <code>Gemfile</code> no raiz da sua aplicação. Entre em <code>config/environment.rb</code>, remova todas as instruções config.gem e as adicione no arquivo <code>Gemfile</code> conforme abaixo, sem o prefixo <code>config.</code> (ponto incluído).</p>
<p>Seu arquivo <code>config/environment.rb</code> era assim:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Be sure to restart your server when you modify this file</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Specifies gem version of Rails to use when vendor/rails is not present</span>
RAILS_GEM_VERSION = <span style="color:#996600;">'2.3.10'</span> <span style="color:#9966CC; font-weight:bold;">unless</span> <span style="color:#9966CC; font-weight:bold;">defined</span>? RAILS_GEM_VERSION
&nbsp;
<span style="color:#008000; font-style:italic;"># Bootstrap the Rails environment, frameworks, and default configuration</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">dirname</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">__FILE__</span><span style="color:#006600; font-weight:bold;">&#41;</span>, <span style="color:#996600;">'boot'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">Rails::Initializer</span>.<span style="color:#9900CC;">run</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>config<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#008000; font-style:italic;"># Settings in config/environments/* take precedence over those specified here.</span>
  <span style="color:#008000; font-style:italic;"># Application configuration should go into files in config/initializers</span>
  <span style="color:#008000; font-style:italic;"># -- all .rb files in that directory are automatically loaded.</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Add additional load paths for your own custom dirs</span>
  <span style="color:#008000; font-style:italic;"># config.load_paths += %W( #{RAILS_ROOT}/extras )</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Specify gems that this application depends on and have them installed with rake gems:install</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;bj&quot;</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;hpricot&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:version</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">'0.6'</span>, <span style="color:#ff3333; font-weight:bold;">:source</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;http://code.whytheluckystiff.net&quot;</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;sqlite3-ruby&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;sqlite3&quot;</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;aws-s3&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;aws/s3&quot;</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;authlogic&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:version</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;=2.1.6&quot;</span>
  config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;slim_scrooge&quot;</span>, <span style="color:#996600;">&quot;=1.0.10&quot;</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Only load the plugins named here, in the order given (default is alphabetical).</span>
  <span style="color:#008000; font-style:italic;"># :all can be used as a placeholder for all plugins not explicitly named</span>
  <span style="color:#008000; font-style:italic;"># config.plugins = [ :exception_notification, :ssl_requirement, :all ]</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Skip frameworks you're not going to use. To use Rails without a database,</span>
  <span style="color:#008000; font-style:italic;"># you must remove the Active Record framework.</span>
  <span style="color:#008000; font-style:italic;"># config.frameworks -= [ :active_record, :active_resource, :action_mailer ]</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>E agora é assim:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;"># Be sure to restart your server when you modify this file</span>
&nbsp;
<span style="color:#008000; font-style:italic;"># Specifies gem version of Rails to use when vendor/rails is not present</span>
RAILS_GEM_VERSION = <span style="color:#996600;">'2.3.10'</span> <span style="color:#9966CC; font-weight:bold;">unless</span> <span style="color:#9966CC; font-weight:bold;">defined</span>? RAILS_GEM_VERSION
&nbsp;
<span style="color:#008000; font-style:italic;"># Bootstrap the Rails environment, frameworks, and default configuration</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC00FF; font-weight:bold;">File</span>.<span style="color:#9900CC;">dirname</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF; font-weight:bold;">__FILE__</span><span style="color:#006600; font-weight:bold;">&#41;</span>, <span style="color:#996600;">'boot'</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#6666ff; font-weight:bold;">Rails::Initializer</span>.<span style="color:#9900CC;">run</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>config<span style="color:#006600; font-weight:bold;">|</span>
  <span style="color:#008000; font-style:italic;"># Settings in config/environments/* take precedence over those specified here.</span>
  <span style="color:#008000; font-style:italic;"># Application configuration should go into files in config/initializers</span>
  <span style="color:#008000; font-style:italic;"># -- all .rb files in that directory are automatically loaded.</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Add additional load paths for your own custom dirs</span>
  <span style="color:#008000; font-style:italic;"># config.load_paths += %W( #{RAILS_ROOT}/extras )</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Only load the plugins named here, in the order given (default is alphabetical).</span>
  <span style="color:#008000; font-style:italic;"># :all can be used as a placeholder for all plugins not explicitly named</span>
  <span style="color:#008000; font-style:italic;"># config.plugins = [ :exception_notification, :ssl_requirement, :all ]</span>
&nbsp;
  <span style="color:#008000; font-style:italic;"># Skip frameworks you're not going to use. To use Rails without a database,</span>
  <span style="color:#008000; font-style:italic;"># you must remove the Active Record framework.</span>
  <span style="color:#008000; font-style:italic;"># config.frameworks -= [ :active_record, :active_resource, :action_mailer ]</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Bem mais limpo, não?</p>
<p>Já o seu recém criado arquivo <code>Gemfile</code> vai ficar assim:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">source <span style="color:#996600;">'http://gemcutter.org'</span>
gem <span style="color:#996600;">&quot;bj&quot;</span>
gem <span style="color:#996600;">&quot;hpricot&quot;</span>, <span style="color:#996600;">&quot;~&gt; 0.6&quot;</span>
gem <span style="color:#996600;">&quot;sqlite3-ruby&quot;</span>, <span style="color:#996600;">&quot;~&gt; 1.3.1&quot;</span>, :<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;sqlite3&quot;</span>
gem <span style="color:#996600;">&quot;aws-s3&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;aws/s3&quot;</span>
gem <span style="color:#996600;">&quot;rails&quot;</span>, <span style="color:#996600;">&quot;= 2.3.10&quot;</span>
gem <span style="color:#996600;">&quot;authlogic&quot;</span>, <span style="color:#996600;">&quot;~&gt; 2.1.6&quot;</span>
&nbsp;
group <span style="color:#ff3333; font-weight:bold;">:development</span>, <span style="color:#ff3333; font-weight:bold;">:test</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  gem <span style="color:#996600;">'mongrel'</span>, :<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0000FF; font-weight:bold;">false</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
group <span style="color:#ff3333; font-weight:bold;">:production</span> <span style="color:#9966CC; font-weight:bold;">do</span>
  gem <span style="color:#996600;">&quot;slim_scrooge&quot;</span>, <span style="color:#996600;">&quot;~&gt; 1.0.10&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Note que eu criei dois grupos: um com <code>:development, :test</code> e um com <code>:production</code>. Significa que as gems do primeiro grupo somente serão utilizadas em desenvolvimento e em testes, e as do segundo grupo somente serão usadas no ambiente de produção. O que está fora dos grupos será usado em qualquer ambiente.</p>
<p>Agora, finalmente você digita <code>bundle install</code>, aguarda alguns instantes e pronto! A sua aplicação está com todas as gems instaladas e suas devidas dependências.</p>
<p>Para listar as gems utilizadas, execute <code>bundle list</code>.</p>
<p>Sugestões, correções e críticas são bem vindas nos comentários.</p>
<p>Para mais informações, leia a documentação no site do Bundle: <a href="http://gembundler.com/" target="_blank">http://gembundler.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2011/01/usando-bundler-com-rails-2-3/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Teste de integração com Rspec 1.x e Capybara na sua app Rails</title>
		<link>http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/</link>
		<comments>http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/#comments</comments>
		<pubDate>Mon, 09 Aug 2010 10:00:35 +0000</pubDate>
		<dc:creator>Roger Leite</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[rspec]]></category>
		<category><![CDATA[ruby on rails]]></category>
		<category><![CDATA[testes unitários]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=704</guid>
		<description><![CDATA[TweetEste não é daqueles posts que explicam o que é rspec, testes, diferenças entre teste funcional, integração e etc. Este post é só uma rapidinha, pra quem já conhece rspec e capybara. A documentação do Capybara é boa, mas deixa a desejar &#8230; <a href="http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/" data-text="Teste de integração com Rspec 1.x e Capybara na sua app Rails" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Este não é daqueles posts que explicam o que é rspec, testes, diferenças entre teste funcional, integração e etc. Este post é só uma rapidinha, pra quem já conhece <a title="Rspec home" href="http://rspec.info/">rspec</a> e <a title="capybara" href="http://github.com/jnicklas/capybara">capybara</a>.</p>
<p>A documentação do Capybara é boa, mas deixa a desejar nas instruções de como integrá-lo somente com rspec. Com a ajuda do <a href="http://blog.georgeguimaraes.com/">George Guimarães</a> da <a href="http://blog.plataformatec.com.br/">Plataforma</a>, cheguei num passo a passo mega simples.</p>
<p>No <em>config/environments/test.rb</em> declare:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;rspec&quot;</span>,            <span style="color:#ff3333; font-weight:bold;">:version</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;= 1.3.0&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#0000FF; font-weight:bold;">false</span>
config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;rspec-rails&quot;</span>,      <span style="color:#ff3333; font-weight:bold;">:version</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;= 1.3.2&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#0000FF; font-weight:bold;">false</span>
config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">&quot;capybara&quot;</span>,         <span style="color:#ff3333; font-weight:bold;">:version</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#996600;">&quot;= 0.3.9&quot;</span>, <span style="color:#ff3333; font-weight:bold;">:lib</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#0000FF; font-weight:bold;">false</span></pre></div></div>

<p>No <em>spec/spec_helper.rb</em> coloque:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'capybara/rails'</span>
<span style="color:#006600; font-weight:bold;">&#91;</span>...<span style="color:#006600; font-weight:bold;">&#93;</span>
<span style="color:#6666ff; font-weight:bold;">Spec::Runner</span>.<span style="color:#9900CC;">configure</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>config<span style="color:#006600; font-weight:bold;">|</span>
&nbsp;
  <span style="color:#006600; font-weight:bold;">&#91;</span>...<span style="color:#006600; font-weight:bold;">&#93;</span>
  config.<span style="color:#9966CC; font-weight:bold;">include</span><span style="color:#006600; font-weight:bold;">&#40;</span>Capybara, <span style="color:#ff3333; font-weight:bold;">:type</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; <span style="color:#ff3333; font-weight:bold;">:integration</span><span style="color:#006600; font-weight:bold;">&#41;</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Pronto! Isto é o suficiente para utilizar o Capybara nos testes de integração.<br />
Para finalizar, você pode montar um teste simples de validação. Por exemplo:</p>
<p>Crie <em>spec/integration/site_spec.rb</em> e coloque:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'spec_helper'</span>
&nbsp;
describe <span style="color:#996600;">&quot;Site sample&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
  context <span style="color:#996600;">&quot;root&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
&nbsp;
    before <span style="color:#9966CC; font-weight:bold;">do</span>
      visit root_url
      save_and_open_page
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
    it <span style="color:#996600;">&quot;should have Hello&quot;</span> <span style="color:#9966CC; font-weight:bold;">do</span>
      page.<span style="color:#9900CC;">should</span> have_content<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;Hello&quot;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Para executar somente os testes de integração:</p>
<pre>rake spec:integration</pre>
<h2>have_content e um hot tip que pode te salvar muitas horas !</h2>
<p>Caso aconteça o erro:</p>
<pre>undefined method `have_content' for #&lt;ActionController::Integration::Session:0xb618ad10&gt;</pre>
<p>Graças a esta mensagem <a href="http://groups.google.com/group/ruby-capybara/browse_thread/thread/28467e031beb7ba1/19a368c21a278eb8?lnk=gst&amp;q=have_content#19a368c21a278eb8">Can&#8217;t make matchers work with cucumber and rails 2.3.2</a>, descobri que o <em>have_content</em> não funciona com o rails 2.3.2, eu resolvi o problema fazendo um upgrade para a última versão do rails. #ficaadica</p>
<p>Dúvidas, melhorias, sugestões e elogios são sempre bem vindos !</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2010/08/teste-de-integracao-com-rspec-1-x-e-capybara-na-sua-app-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Gerando rotas com parâmetros dinâmicos no Rails de modo fácil</title>
		<link>http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/</link>
		<comments>http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 09:00:23 +0000</pubDate>
		<dc:creator>Rodrigo Panachi</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[web]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=680</guid>
		<description><![CDATA[TweetA API de rotas do Rails simplifica consideravelmente o desenvolvimento fornecendo um padrão de geração e utilização de URLs para toda aplicação. Porém algumas necessidades especificas e relativamente simples podem gerar dores de cabeça se forem implementadas incorretamente. Um caso bastante &#8230; <a href="http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/" data-text="Gerando rotas com parâmetros dinâmicos no Rails de modo fácil" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>A <a href="http://api.rubyonrails.org/classes/ActionController/Routing.html">API de rotas</a> do Rails simplifica consideravelmente o desenvolvimento fornecendo um padrão de geração e utilização de URLs para toda aplicação. Porém algumas necessidades especificas e relativamente simples podem gerar dores de cabeça se forem implementadas incorretamente.</p>
<p>Um caso bastante comum são URLs compostas que sempre apontam para um mesmo recurso. Por exemplo, um blog que possua rotas para seus posts no formato <code>/posts/autor/categoria/permalink</code> provavelmente terá uma rota mapeada como <code>map.post "posts/:author/:category/:permalink"</code> gerando automaticamente os helpers <code>post_path</code> e <code>post_url</code>.</p>
<p>Muito bom, porém para <a href="http://guides.rubyonrails.org/routing.html#generating-urls-from-code">usufruirmos desta facilidade</a> precisamos fornecer os valores dos parâmetros dinâmicos nos <em>controllers</em> e <em>views</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">post_path<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:author</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">author</span>, <span style="color:#ff3333; font-weight:bold;">:category</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">category</span>, <span style="color:#ff3333; font-weight:bold;">:permalink</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">permalink</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>E mesmo que você forneça os <a href="http://guides.rubyonrails.org/routing.html#route-generation-from-arrays">parâmetros em um array</a>, vai dar muito trabalho além de deixar muito código repetido pela aplicação.</p>
<h2>Entendi! Mas como resolvo este problema?</h2>
<p>Para este caso, apenas implementar o método <code><a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001840">to_param</a></code> do model não vai servir. Uma solução seria reescrever o método <code>post_path</code> (que é gerado automaticamente) no respectivo helper (posts_helper.rb):</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> post_path<span style="color:#006600; font-weight:bold;">&#40;</span>post, options = <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;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">super</span><span style="color:#006600; font-weight:bold;">&#40;</span>post, <span style="color:#ff3333; font-weight:bold;">:author</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> post.<span style="color:#9900CC;">author</span>, <span style="color:#ff3333; font-weight:bold;">:category</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> post.<span style="color:#9900CC;">category</span>, <span style="color:#ff3333; font-weight:bold;">:permalink</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> post.<span style="color:#9900CC;">permalink</span><span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Outra solução seria sobrescrever o método <code><a href="http://api.rubyonrails.org/classes/ActionController/Base.html#M000467">default_url_options</a></code> no <em>controller</em> para retorna os parâmetros padrões da rota:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> default_url_options<span style="color:#006600; font-weight:bold;">&#40;</span>options = <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;">&#41;</span>
  options.<span style="color:#9900CC;">merge</span>!<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:author</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">author</span>, <span style="color:#ff3333; font-weight:bold;">:category</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">category</span>, <span style="color:#ff3333; font-weight:bold;">:permalink</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#0066ff; font-weight:bold;">@post</span>.<span style="color:#9900CC;">permalink</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">if</span> options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:action</span><span style="color:#006600; font-weight:bold;">&#93;</span> == <span style="color:#996600;">&quot;show&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>A má notícia é que você terá que fazer isto para todos seus controllers e respectivos models.</p>
<p>A terceira solução (e mais elegante) é padronizar a maneira com que os parâmetros opcionais da rota são obtidos a partir do controller e seu respectivo model. Basta adicionar os seguintes métodos no seu <em>ApplicationController</em>:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> default_url_options<span style="color:#006600; font-weight:bold;">&#40;</span>options = <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;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#006600; font-weight:bold;">&#40;</span>model = controller_model<span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    dynamic_route_params<span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>param<span style="color:#006600; font-weight:bold;">|</span>
      options<span style="color:#006600; font-weight:bold;">&#91;</span>param<span style="color:#006600; font-weight:bold;">&#93;</span> = model.<span style="color:#9900CC;">send</span><span style="color:#006600; font-weight:bold;">&#40;</span>param<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#9966CC; font-weight:bold;">if</span> model.<span style="color:#9900CC;">respond_to</span>?<span style="color:#006600; font-weight:bold;">&#40;</span>param<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  options
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> controller_model<span style="color:#006600; font-weight:bold;">&#40;</span>options = <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;">&#41;</span>
  clazz = <span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">&#93;</span>.<span style="color:#9900CC;">singularize</span>.<span style="color:#9900CC;">camelize</span>.<span style="color:#9900CC;">constantize</span> <span style="color:#9966CC; font-weight:bold;">rescue</span> ActiveRecord<span style="color:#006600; font-weight:bold;">&#41;</span>
  options.<span style="color:#CC0066; font-weight:bold;">select</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#006600; font-weight:bold;">|</span>key, value<span style="color:#006600; font-weight:bold;">|</span> value.<span style="color:#9900CC;">is_a</span>?<span style="color:#006600; font-weight:bold;">&#40;</span>clazz<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">first</span>.<span style="color:#9900CC;">second</span>
<span style="color:#9966CC; font-weight:bold;">rescue</span>
  <span style="color:#0000FF; font-weight:bold;">nil</span>
<span style="color:#9966CC; font-weight:bold;">end</span> 
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> dynamic_route_params<span style="color:#006600; font-weight:bold;">&#40;</span>options = <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;">&#41;</span>
  returning <span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>dynamic_params<span style="color:#006600; font-weight:bold;">|</span>
    matched_routes = <span style="color:#6666ff; font-weight:bold;">ActionController::Routing::Routes</span>.<span style="color:#9900CC;">routes</span>.<span style="color:#CC0066; font-weight:bold;">select</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>route<span style="color:#006600; font-weight:bold;">|</span>
      route.<span style="color:#9900CC;">matches_controller_and_action</span>?<span style="color:#006600; font-weight:bold;">&#40;</span>options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:controller</span><span style="color:#006600; font-weight:bold;">&#93;</span>, options<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:action</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    dynamic_segments = matched_routes.<span style="color:#9900CC;">map</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&amp;</span>:segments<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">flatten</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>segment<span style="color:#006600; font-weight:bold;">|</span>
      dynamic_params <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> segment.<span style="color:#9900CC;">key</span> <span style="color:#9966CC; font-weight:bold;">if</span> segment.<span style="color:#9900CC;">is_a</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#6666ff; font-weight:bold;">ActionController::Routing::DynamicSegment</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Assim, os valores defaults dos parâmetros da rota serão obtidos diretamente do model. Caso queiram contribuir, este código está disponível no <a href="http://github.com/1up4dev/random-samples/blob/master/dynamic_route_params/dynamic_route_params.rb">github</a>.</p>
<p><strong>Referências</strong><br />
<a href="http://railsguts.com/routing_inside_out.html">Rails Routing from the Inside Out</a><br />
<a href="http://guides.rubyonrails.org/routing.html">Rails Guides: Routing</a></p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2010/07/gerando-rotas-com-parametros-dinamicos-no-rails-de-modo-facil/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Active Record em: Como adicionar comportamento as suas associações</title>
		<link>http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/</link>
		<comments>http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/#comments</comments>
		<pubDate>Wed, 19 May 2010 13:14:18 +0000</pubDate>
		<dc:creator>Roger Leite</dc:creator>
				<category><![CDATA[quick tips]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[real world]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[active record]]></category>
		<category><![CDATA[pragmatismo]]></category>
		<category><![CDATA[ruby on rails]]></category>

		<guid isPermaLink="false">http://1up4dev.org/?p=657</guid>
		<description><![CDATA[TweetQualquer um que comece a desenvolver com Active Record (AR), minha primeira recomendação é, para tudo e leia:  A Guide to Active Record Associations ou O Guia de Associações do Active Record. O guia é bem completo, e descreve muito &#8230; <a href="http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/">Continue lendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="socialize-in-content" style="float:left;"><div class="socialize-in-button socialize-in-button-left"><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/" data-text="Active Record em: Como adicionar comportamento as suas associações" data-count="vertical" data-via="socializeWP" >Tweet</a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div class="socialize-in-button socialize-in-button-left"><iframe src="http://www.facebook.com/plugins/like.php?href=http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/&amp;layout=box_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=65" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:50px !important; height:65px;" allowTransparency="true"></iframe></div></div><p>Qualquer um que comece a desenvolver com <a href="http://api.rubyonrails.org/files/vendor/rails/activerecord/README.html">Active Record</a> (AR), minha primeira recomendação é, para tudo e leia:  <a href="http://guides.rubyonrails.org/association_basics.html">A Guide to Active Record Associations</a> ou <a href="http://guias.rubyonrails.pro.br/association_basics.html">O Guia de Associações do Active Record</a>. O guia é bem completo, e descreve muito bem os tipos de associações que estão disponíveis no AR.</p>
<h2>Association Proxy, #wtf !</h2>
<p>As associações:</p>
<ul>
<li>belongs_to</li>
<li>has_one</li>
<li>has_many</li>
<li>has_and_belongs_to_many</li>
</ul>
<p>Quando usadas, adicionam alguns métodos (veja <a href="http://guides.rubyonrails.org/association_basics.html#detailed-association-reference">Detailed Association Reference</a>). Por exemplo, ao declarar uma associação <em>belongs_to</em>, o model &#8220;ganhará&#8221; os seguintes métodos:</p>
<ul>
<li>association(force_reload = false)</li>
<li>association=(associate)</li>
<li>build_association(attributes = {})</li>
<li>create_association(attributes = {})</li>
</ul>
<p>Onde association, será substituído pelo nome da associação. Exemplo retirado do guides:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Order <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
   belongs_to <span style="color:#ff3333; font-weight:bold;">:customer</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Cada instância de Order, conterá os métodos:</p>
<p><span style="font-size: small;"> </span></p>
<ul>
<li>customer</li>
<li>customer=</li>
<li>build_customer</li>
<li>create_customer</li>
</ul>
<p>O <em>association proxy</em>, é o objeto que faz a ligação do objeto que contém a associação, conhecido como <em>owner</em>, e o objeto associado, conhecido como <em>target</em>.</p>
<h2>Legal e daí !?!</h2>
<p>Graças ao <em>association proxy</em>, ao declarar uma associação, podemos extendê-la e adicionar comportamentos &#8220;customizados&#8221;. No guia, é citado como <a href="http://guides.rubyonrails.org/association_basics.html#association-extensions">Association Extensions</a>. O código de exemplo abaixo, está no github em <a href="http://github.com/rogerleite/random-samples">random-samples</a>.</p>
<p>Para exemplificar, vamos criar um modulo que adiciona o comportamento de uma galeria a qualquer coleção.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> GalleryColletion
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> current=<span style="color:#006600; font-weight:bold;">&#40;</span>curr = <span style="color:#0000FF; font-weight:bold;">nil</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#0066ff; font-weight:bold;">@current</span>, <span style="color:#0066ff; font-weight:bold;">@index</span> = <span style="color:#0000FF; font-weight:bold;">nil</span>
&nbsp;
    <span style="color:#9966CC; font-weight:bold;">if</span> curr.<span style="color:#0000FF; font-weight:bold;">nil</span>?
      <span style="color:#0066ff; font-weight:bold;">@current</span> = collection.<span style="color:#9900CC;">first</span>
      <span style="color:#0066ff; font-weight:bold;">@index</span> = <span style="color:#006666;">0</span>
    <span style="color:#9966CC; font-weight:bold;">else</span>
      collection.<span style="color:#9900CC;">each_with_index</span> <span style="color:#9966CC; font-weight:bold;">do</span> <span style="color:#006600; font-weight:bold;">|</span>item, index<span style="color:#006600; font-weight:bold;">|</span>
        <span style="color:#9966CC; font-weight:bold;">if</span> item.<span style="color:#9900CC;">id</span>.<span style="color:#9900CC;">to_i</span> == curr.<span style="color:#9900CC;">to_i</span>
          <span style="color:#0066ff; font-weight:bold;">@current</span> = item
          <span style="color:#0066ff; font-weight:bold;">@index</span> = index
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#9966CC; font-weight:bold;">end</span>
    <span style="color:#0066ff; font-weight:bold;">@current</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> current
    <span style="color:#0066ff; font-weight:bold;">@current</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> position
    <span style="color:#0066ff; font-weight:bold;">@index</span> <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#006666;">1</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> previous?
    <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0066ff; font-weight:bold;">@index</span>.<span style="color:#0000FF; font-weight:bold;">nil</span>?
    !!<span style="color:#006600; font-weight:bold;">&#40;</span>@index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&gt;</span>= <span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> previous
    collection<span style="color:#006600; font-weight:bold;">&#91;</span>@index <span style="color:#006600; font-weight:bold;">-</span> <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#9966CC; font-weight:bold;">if</span> previous?
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#9966CC; font-weight:bold;">next</span>?
    <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#0000FF; font-weight:bold;">false</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0066ff; font-weight:bold;">@index</span>.<span style="color:#0000FF; font-weight:bold;">nil</span>?
    !!<span style="color:#006600; font-weight:bold;">&#40;</span>@index <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#006666;">1</span> <span style="color:#006600; font-weight:bold;">&lt;</span> collection.<span style="color:#9900CC;">size</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#9966CC; font-weight:bold;">next</span>
    collection<span style="color:#006600; font-weight:bold;">&#91;</span>@index <span style="color:#006600; font-weight:bold;">+</span> <span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#9966CC; font-weight:bold;">next</span>?
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  private
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> collection
    proxy_owner.<span style="color:#9900CC;">send</span><span style="color:#006600; font-weight:bold;">&#40;</span>proxy_reflection.<span style="color:#9900CC;">name</span><span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><a href="http://github.com/rogerleite/random-samples/blob/master/association_extend/lib/extensions/gallery_collection.rb">Gallery Collection</a></p>
<p>Note que o modulo está na pasta lib, logo, a pasta tem que ser adicionada no path via config/environment.rb.</p>
<p>Para extender a associação, declare:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> Article <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>
  has_and_belongs_to_many <span style="color:#ff3333; font-weight:bold;">:images</span>, <span style="color:#ff3333; font-weight:bold;">:extend</span> <span style="color:#006600; font-weight:bold;">=&gt;</span> GalleryColletion
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p><a href="http://github.com/rogerleite/random-samples/blob/master/association_extend/app/models/article.rb">Article model</a>, <a href="http://github.com/rogerleite/random-samples/blob/master/association_extend/app/models/image.rb">Image model aqui</a>.</p>
<p>Agora para navegar entre as imagens, você pode usar:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby" style="font-family:monospace;">a = Article.<span style="color:#9900CC;">first</span>
a.<span style="color:#9900CC;">images</span>.<span style="color:#9900CC;">current</span> = <span style="color:#006666;">1</span> <span style="color:#008000; font-style:italic;">#1 e o Image.id que deseja selecionar</span>
a.<span style="color:#9900CC;">images</span>.<span style="color:#9900CC;">current</span>
a.<span style="color:#9900CC;">images</span>.<span style="color:#9900CC;">position</span>
a.<span style="color:#9900CC;">images</span>.<span style="color:#9966CC; font-weight:bold;">next</span>?
a.<span style="color:#9900CC;">images</span>.<span style="color:#9966CC; font-weight:bold;">next</span>
a.<span style="color:#9900CC;">images</span>.<span style="color:#9900CC;">previous</span>?
a.<span style="color:#9900CC;">images</span>.<span style="color:#9900CC;">previous</span></pre></div></div>

<p>Caso esteja com coragem, baixe o projeto e veja rodando.</p>
<p>Dúvidas, sugestões, algum &#8220;case&#8221; de sucesso, comente!</p>
]]></content:encoded>
			<wfw:commentRss>http://1up4dev.org/2010/05/active-record-em-como-adicionar-comportamento-as-suas-associacoes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

