<?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>Saga do programador &#187; busca de cep</title>
	<atom:link href="http://www.sagadoprogramador.com.br/tag/busca-de-cep/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sagadoprogramador.com.br</link>
	<description></description>
	<lastBuildDate>Wed, 18 Aug 2010 13:34:02 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Receita para um formulário com busca de cep à la Rails :p</title>
		<link>http://www.sagadoprogramador.com.br/2008/11/receita-para-um-formulario-com-busca-de-cep-a-la-rails-p/</link>
		<comments>http://www.sagadoprogramador.com.br/2008/11/receita-para-um-formulario-com-busca-de-cep-a-la-rails-p/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 16:47:18 +0000</pubDate>
		<dc:creator>Iuri Menescal</dc:creator>
				<category><![CDATA[Rails]]></category>
		<category><![CDATA[Tutoriais]]></category>
		<category><![CDATA[brazilian-rails]]></category>
		<category><![CDATA[busca de cep]]></category>
		<category><![CDATA[Jquery]]></category>
		<category><![CDATA[JSon]]></category>

		<guid isPermaLink="false">http://www.sagadoprogramador.com.br/?p=23</guid>
		<description><![CDATA[Receita para um formulário com busca de cep  utilizando Rails, Brazilian-Rails, Jquery e JSon]]></description>
			<content:encoded><![CDATA[<p><strong>Ingredientes:</strong></p>
<ul>
<li>Brazilian-rails</li>
<li>Jquery</li>
<li>Ruby-json</li>
</ul>
<p><strong>Modo de preparo:</strong></p>
<p>Coloque uma porção generosa de utilitários que facilitam o dia a dia de nos Brasileiros em seu caldeirão Rails:</p>
<pre>&gt; gem --install brazilian-rails</pre>
<p><em>"O gem brazilian-rails possui vários ingredientes para temperar a sua aplicação, mas no momento vamos nos concentrar na busca por cep. Você pode saber mais sobre o brazilian-rails no site da <a href="http://www.improveit.com.br/software_livre/brazilian_rails">improve It</a>."</em><span id="more-23"></span></p>
<p>Em seguida acrescente uma medida de ruby-json:</p>
<pre>&gt; gem –install ruby-json</pre>
<p><em>"O ruby-json é um utilitário para serializar as suas classes ruby para os padrões Json."</em></p>
<p>Só para lembrar vamos utilizar Jquery também, mas isso já é um ingrediente padrão em qualquer receita Web sua, certo?<br />
Não?? Como assim? Você ainda não utiliza JQuery? putz.. tsc.. tsc..<br />
Se você ainda não usa, chegou a hora. <a href="http://jquery.com">http://jquery.com/</a> Instale na pasta /public/javascript na estrutura de diretórios do seu projeto Rails.</p>
<p>(Pretendo colocar alguns tutoriais de Jquery aqui no blog em breve ou nem tão breve assim rs.. <em>"O blog é meu e eu post a hora que eu quiser hahahaa!"</em>)</p>
<p>Bom, agora que temos todos os ingredientes necessários em seus devidos lugares, deixe eles cozinhando em quanto preparamos o nosso prato.</p>
<p>No controller, vamos criar um método para fazer a busca do cep e retornar o resultado para o cliente utilizando Json.<br />
<strong>Você já tem o seu formulário pronto né? (model, view, controller)</strong></p>
<p>Não??<br />
<strong> **##%%!!</strong><br />
Você só quer moleza em? :p</p>
<p>Quer tudo na mão! ok ok vou fazer do zero, mas vê se presta atenção nessa porra e não vai só copiar e colar o código, pois é tão fácil que até comigo explicando você vai entender hehehe!</p>
<p>Vamos criar um controller:</p>
<pre> &gt; script/generate controller enderecos</pre>
<p>Em seguida edite o seu controller enderecos_controller.rb</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;"><span style="color:#008000; font-style:italic;">#classe do utilitario para serializar as classes ruby para o padrão json</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'json/objects'</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> localizar_endereco
      retorno = <span style="color:#006666;">1</span>
      <span style="color:#008000; font-style:italic;"># Classe do brazilian-rails responsavél pela busca de endereco.</span>
      <span style="color:#0066ff; font-weight:bold;">@endereco</span> = BuscaEndereco.<span style="color:#9900CC;">por_cep</span> params<span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:cep</span><span style="color:#006600; font-weight:bold;">&#93;</span>
      endereco = <span style="color:#0066ff; font-weight:bold;">@endereco</span>.<span style="color:#9900CC;">fetch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">0</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      numero = <span style="color:#0066ff; font-weight:bold;">@endereco</span>.<span style="color:#9900CC;">fetch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      bairro = <span style="color:#0066ff; font-weight:bold;">@endereco</span>.<span style="color:#9900CC;">fetch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">2</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      estado = <span style="color:#0066ff; font-weight:bold;">@endereco</span>.<span style="color:#9900CC;">fetch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">3</span><span style="color:#006600; font-weight:bold;">&#41;</span>
      cidade = <span style="color:#0066ff; font-weight:bold;">@endereco</span>.<span style="color:#9900CC;">fetch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006666;">4</span><span style="color:#006600; font-weight:bold;">&#41;</span>
     <span style="color:#9966CC; font-weight:bold;">rescue</span>
        retorno = <span style="color:#006666;">0</span>
     <span style="color:#9966CC; font-weight:bold;">ensure</span>
        <span style="color:#008000; font-style:italic;"># preste atenção nesse bloco e veja como é dificil serializar um objeto JSon no Ruby</span>
        <span style="color:#008000; font-style:italic;"># objeto = {:nome do atributo =&amp;gt; valor do atributo}</span>
        data = <span style="color:#006600; font-weight:bold;">&#123;</span>:retorno =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; retorno, <span style="color:#ff3333; font-weight:bold;">:endereco</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; endereco,
                <span style="color:#ff3333; font-weight:bold;">:bairro</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; bairro, <span style="color:#ff3333; font-weight:bold;">:cidade</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; cidade, <span style="color:#ff3333; font-weight:bold;">:estado</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; estado<span style="color:#006600; font-weight:bold;">&#125;</span>
    render <span style="color:#ff3333; font-weight:bold;">:text</span> =<span style="color:#006600; font-weight:bold;">&amp;</span>gt; data.<span style="color:#9900CC;">to_json</span>  <span style="color:#008000; font-style:italic;">#aqui acontece a mágica!</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Vamos criar um formulário para testar a nosso busca:<br />
Crie um arquivo /app/views/enderecos/index.html.erb e logo depois da tag "html" insira o código abaixo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">  &lt;!-- Arquivo do framework jquery --&gt;
  &lt;script src=&quot;/javascripts/jquery.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  Busca de endereço por cep
&lt;!-- Aqui vai o nosso código utilizando Jquery --&gt;
<span style="color: #339933;">&lt;</span>script type<span style="color: #339933;">=</span><span style="color: #3366CC;">&quot;text/javascript&quot;</span><span style="color: #339933;">&gt;</span>
$<span style="color: #009900;">&#40;</span>document<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">ready</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
 $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#btncep&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>$.<span style="color: #660066;">trim</span><span style="color: #009900;">&#40;</span>endereco_cep.<span style="color: #660066;">value</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 
    <span style="color: #339933;">&lt;!--</span> Aqui é uma firula<span style="color: #339933;">,</span> para o usuário não achar que não esta acontecendo nada<span style="color: #339933;">--&gt;</span>
      $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#lbcep&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot; Pesquisando cep...&quot;</span><span style="color: #009900;">&#41;</span>
	<span style="color: #339933;">&lt;!--</span> função <span style="color: #000066; font-weight: bold;">do</span> JQuery que Recebe o objeto serializado via ajax. <span style="color: #339933;">--&gt;</span>
        <span style="color: #339933;">&lt;!--</span> Ta vendo como o JQuery é foda<span style="color: #339933;">?</span> <span style="color: #339933;">--&gt;</span>
      $.<span style="color: #660066;">getJSON</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;/enderecos/localizar_endereco&quot;</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> cep<span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_cep&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>json<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #339933;">&lt;!--</span> Atribuindo os valores para os componentes da página<span style="color: #339933;">--&gt;</span>
	<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>json.<span style="color: #660066;">retorno</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_endereco&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span>json.<span style="color: #660066;">endereco</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_bairro&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span>json.<span style="color: #660066;">bairro</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_cidade&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span>json.<span style="color: #660066;">cidade</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_estado&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">val</span><span style="color: #009900;">&#40;</span>json.<span style="color: #660066;">estado</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#endereco_numero&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #000066;">focus</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   <span style="color: #009900;">&#125;</span> <span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
	      <span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Cep não encontrado.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	   <span style="color: #009900;">&#125;</span>
	   $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;#lbcep&quot;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot; cep:&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span> 
	<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Informe um cep.&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #339933;">&lt;/</span>script<span style="color: #339933;">&gt;</span></pre></td></tr></table></div>

<p>Agora vamos colocar o código do formulário no "body" da nossa página:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="html" style="font-family:monospace;">&lt;body&gt;
&lt;form id=&quot;frmBuscaCep&quot; &gt;
  &lt;fieldset&gt;
    &lt;legend&gt;Endereço&lt;/legend&gt;
    &lt;table&gt;
      &lt;tr&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_cep&quot; id=&quot;lbcep&quot;&gt; cep:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_cep&quot; name=&quot;endereco[cep]&quot; size=&quot;12&quot; /&gt;
	&lt;a id=&quot;btncep&quot; href=&quot;#&quot;&gt; Pesquisar Cep&lt;/a&gt;&lt;span id=&quot;msgbuscacep&quot;&gt;&lt;/span&gt;
      &lt;/td&gt;&lt;/tr&gt;
     &lt;tr&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_endereco&quot;&gt; endereco:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_endereco&quot; name=&quot;endereco[endereco]&quot; size=&quot;50&quot; /&gt;
     &lt;/td&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_numero&quot;&gt; numero:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_numero&quot; name=&quot;endereco[numero]&quot; size=&quot;10&quot; /&gt;			  
     &lt;/td&gt;&lt;/tr&gt;
   &lt;/table&gt;	
   &lt;table&gt;	
     &lt;tr&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_bairro&quot;&gt; bairro:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_bairro&quot; name=&quot;endereco[bairro]&quot; size=&quot;20&quot; /&gt;
     &lt;/td&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_cidade&quot;&gt; cidade:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_cidade&quot; name=&quot;endereco[cidade]&quot; size=&quot;20&quot; /&gt;
     &lt;/td&gt;&lt;td&gt;
	&lt;label for=&quot;endereco_estado&quot;&gt; estado:&lt;/label&gt;&lt;br /&gt;
	&lt;input type=&quot;text&quot; id=&quot;endereco_estado&quot; name=&quot;endereco[estado]&quot; size=&quot;5&quot; /&gt;
     &lt;/td&gt;&lt;/tr&gt;
   &lt;/table&gt; 
 &lt;/fieldset&gt;
&lt;/form&gt;
&lt;/body&gt;</pre></td></tr></table></div>

<p>Ufa!! terminamos <img src='http://www.sagadoprogramador.com.br/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /><br />
Agora é só iniciar o seu servidor:</p>
<pre> >> script/server </pre>
<p>e acessar o endereço: http://localhost:3000/enderecos<br />
E ai funcionou?<br />
...<br />
...<br />
..<br />
Não?? como assim? vc acompanhou o tutorial todo?<br />
#!**#$!!!<br />
Eu falei para você não ficar só copiando e colando o código....</p>
<p>HAHHAAA!! brincadeira, ainda falta um pequeno detalhe <img src='http://www.sagadoprogramador.com.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /><br />
edite o arquivo: config/environment.rb</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="ruby" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#6666ff; font-weight:bold;">Rails::VERSION::STRING</span> <span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#996600;">'2.0.2'</span>
    config.<span style="color:#9900CC;">gem</span> <span style="color:#996600;">'brazilian-rails'</span>
  <span style="color:#9966CC; font-weight:bold;">else</span>
    <span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'brazilian-rails'</span>
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Agora sim é só testar!</p>
<p>Abraço!<br />
Iuri</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sagadoprogramador.com.br/2008/11/receita-para-um-formulario-com-busca-de-cep-a-la-rails-p/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
