<?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>Bicosyes - since evermore... &#187; Ruby</title>
	<atom:link href="http://bicosyes.com/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://bicosyes.com</link>
	<description></description>
	<lastBuildDate>Sat, 06 Mar 2010 20:03:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to know, in ruby, which methods have been added and by whom?</title>
		<link>http://bicosyes.com/how-to-know-in-ruby-which-methods-have-been-added-and-by-whom/</link>
		<comments>http://bicosyes.com/how-to-know-in-ruby-which-methods-have-been-added-and-by-whom/#comments</comments>
		<pubDate>Mon, 23 Nov 2009 19:50:37 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[english]]></category>
		<category><![CDATA[method_added]]></category>
		<category><![CDATA[monkeypatching]]></category>

		<guid isPermaLink="false">http://bicosyes.com/?p=885</guid>
		<description><![CDATA[If you are not very careful, monkeypatching could be very harmful. One thing to remember is that you should never override a method to add funcionality, for those kind of thinks you must use alias chain method pattern, a safer &#8230; <a href="http://bicosyes.com/how-to-know-in-ruby-which-methods-have-been-added-and-by-whom/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>If you are not very careful, monkeypatching could be very harmful. One thing to remember is that you should <strong>never</strong> override a method to <strong>add</strong> funcionality, for those kind of thinks you must use <em>alias chain method pattern</em>, a safer way of doing that. </p>
<p>For the rest of the <em>monkeypatching</em>, i.e. add new methods, you could debug them really easy with something like this:</p>
<pre class="ruby"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#9966CC; font-weight:bold;">Class</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> method_added<span style="color:#006600; font-weight:bold;">&#40;</span>method_name<span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;#{method_name} added to #{self}, callstack:&quot;</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#CC0066; font-weight:bold;">caller</span>.<span style="color:#9900CC;">map</span><span style="color:#006600; font-weight:bold;">&#123;</span>|line| <span style="color:#996600;">&quot;<span style="color:#000099;">\t</span>#{line}&quot;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;<span style="color:#000099;">\n</span>&quot;</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>
<p>You can always add more code to filter by class or by method's name. Let's see an example:</p>
<pre class="ruby">$ more example.<span style="color:#9900CC;">rb</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'date'</span>
<span style="color:#CC0066; font-weight:bold;">require</span> <span style="color:#996600;">'time'</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#9966CC; font-weight:bold;">Class</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> method_added<span style="color:#006600; font-weight:bold;">&#40;</span>method_name<span style="color:#006600; font-weight:bold;">&#41;</span>
      <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#9966CC; font-weight:bold;">if</span> %w<span style="color:#006600; font-weight:bold;">&#40;</span>method_added<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9966CC; font-weight:bold;">include</span>? method_name.<span style="color:#9900CC;">to_s</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#996600;">&quot;#{method_name} added to #{self}, callstack:&quot;</span>
      <span style="color:#CC0066; font-weight:bold;">puts</span> <span style="color:#CC0066; font-weight:bold;">caller</span>.<span style="color:#9900CC;">map</span><span style="color:#006600; font-weight:bold;">&#123;</span>|line| <span style="color:#996600;">&quot;<span style="color:#000099;">\t</span>#{line}&quot;</span> <span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">join</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">&quot;<span style="color:#000099;">\n</span>&quot;</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>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Time</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> to_date
      <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">ordinal</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">year</span>, <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">yday</span>
   <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Date</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> to_time
      <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">parse</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">to_s</span>
   <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#996600;">&quot;to_date not working&quot;</span> <span style="color:#9966CC; font-weight:bold;">unless</span>
   <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">to_date</span> == <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">today</span>
<span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#996600;">&quot;to time not working&quot;</span> <span style="color:#9966CC; font-weight:bold;">unless</span>
   <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">to_date</span>.<span style="color:#9900CC;">to_time</span> == <span style="color:#CC00FF; font-weight:bold;">Date</span>.<span style="color:#9900CC;">today</span>.<span style="color:#9900CC;">to_time</span></pre>
<p>The output will be:</p>
<pre>$ ruby example.rb
to_date added to Time, callstack:
	example.rb:13
to_time added to Date, callstack:
	example.rb:19</pre>
<p>Nice, isn't it?. Remember to be carefull with your monkeypatching, with great power comes great responsibility, it's just a tool, neither magic nor the panacea.</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=885&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/how-to-know-in-ruby-which-methods-have-been-added-and-by-whom/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visualización de la documentación de todas las gemas instaladas</title>
		<link>http://bicosyes.com/visualizacion-de-la-documentacion-de-todas-las-gemas-instaladas/</link>
		<comments>http://bicosyes.com/visualizacion-de-la-documentacion-de-todas-las-gemas-instaladas/#comments</comments>
		<pubDate>Sun, 31 May 2009 12:55:10 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[bdoc]]></category>
		<category><![CDATA[gems]]></category>
		<category><![CDATA[rdoc]]></category>

		<guid isPermaLink="false">http://bicosyes.com/?p=835</guid>
		<description><![CDATA[La documentación de las gemas de ruby se genera a partir del código fuente mediante rdoc. Después de eso puedes optar por ver individualmente cada una o usar gem server. Para poder mejorar todo esto podemos usar par de útiles &#8230; <a href="http://bicosyes.com/visualizacion-de-la-documentacion-de-todas-las-gemas-instaladas/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>La documentación de las gemas de ruby se genera a partir del código fuente mediante rdoc. Después de eso puedes optar por ver individualmente cada una o usar <a href="http://rubygems.org/read/chapter/18">gem server</a>.</p>
<p>Para poder mejorar todo esto podemos usar par de útiles herramientas: (1) la plantilla para rdoc, <strong><a href="http://github.com/mislav/hanna/tree/master">hanna</a></strong>; y (2)<a href="http://manalang.com/archives/2009/03/29/introducing-bdoc-a-better-gem-doc-browser/"><strong>bdoc</strong></a> como alternativa a gem server para visualizar la documentación.</p>
<p><strong>Hanna</strong> es una plantilla para rdoc que mejora notablemente el formato por defecto. Podemos ver la diferencia fácilmente, por ejemplo, en la documentación de rspec con <a href="http://rspec.rubyforge.org/rspec/1.1.11/">el formato típico</a> <em>vs</em> <a href="http://rspec.rubyforge.org/rspec/1.2.6/">la documentación hecha con hanna</a>. La instalación es simple:</p>
<pre class="bash">$ <span style="color: #c20cb9; font-weight: bold;">sudo</span> gem sources -a http://gems.github.com
$ <span style="color: #c20cb9; font-weight: bold;">sudo</span> gem <span style="color: #c20cb9; font-weight: bold;">install</span> mislav-hanna</pre>
<p>Para que a partir de ahora se generar la documentación con esta plantilla, puede añadir a tu <em>.gemrc</em> la siguiente línea:</p>
<pre>rdoc: --inline-source --line-numbers --template=hanna</pre>
<p>Y para convertir la documentación de todas tus gemas instaladas, puedes hacer algo como esto:</p>
<pre class="bash">$ <span style="color: #c20cb9; font-weight: bold;">sudo</span> gem list | <span style="color: #c20cb9; font-weight: bold;">awk</span> <span style="color: #ff0000;">'{print $1}'</span> | <span style="color: #c20cb9; font-weight: bold;">xargs</span> <span style="color: #c20cb9; font-weight: bold;">sudo</span> hanna --gems</pre>
<p>Por otro lado, gracias a <strong>bdoc</strong> podremos navegar fácilmente entre todas las documentaciones.</p>
<pre class="bash">$ <span style="color: #c20cb9; font-weight: bold;">sudo</span> gem <span style="color: #c20cb9; font-weight: bold;">install</span> manalang-bdoc
$ bdoc</pre>
<p><a href="http://bicosyes.com/wp-content/uploads/2009/05/bdoc.jpg"><img src="http://bicosyes.com/wp-content/uploads/2009/05/bdoc-300x157.jpg" alt="bdoc" title="bdoc" width="300" height="157" class="aligncenter size-medium wp-image-836" /></a><br />
Ejecutando <em>bdoc</em> se nos abrirá en nuestro navegador por defecto listo para poder leer la documentación y poder movernos fácilmente entre las diferentes gemas (y versiones). Muy útil.</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=835&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/visualizacion-de-la-documentacion-de-todas-las-gemas-instaladas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bot personal jabber para twitter, RTwittBot</title>
		<link>http://bicosyes.com/bot-personal-jabber-para-twitter-rtwittbot/</link>
		<comments>http://bicosyes.com/bot-personal-jabber-para-twitter-rtwittbot/#comments</comments>
		<pubDate>Sun, 31 Aug 2008 15:03:29 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[bot]]></category>
		<category><![CDATA[jabber]]></category>
		<category><![CDATA[twitter]]></category>
		<category><![CDATA[twitter4r]]></category>
		<category><![CDATA[xmpp]]></category>
		<category><![CDATA[xmpp4r]]></category>

		<guid isPermaLink="false">http://bicosyes.com/?p=645</guid>
		<description><![CDATA[Desde hace ya un tiempo llevo usando twitter, y no, no tiene ninguna utilidad, pero me gusta hablar solo (¡está loco!). Twitter se cae cada dos por tres, pero era algo que se puede soportar (así siempre tienes algo que &#8230; <a href="http://bicosyes.com/bot-personal-jabber-para-twitter-rtwittbot/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Desde hace ya un tiempo llevo usando <a href="http://twitter.com/blaxter">twitter</a>, y no, no tiene ninguna utilidad, pero me gusta hablar solo (¡está loco!). <a href="http://status.twitter.com">Twitter</a> se cae cada dos por tres, pero era algo que se puede soportar (así siempre tienes algo que decir... y de lo que quejarte que a todos nos gusta quejarnos, ¡quejicas!), pero desde Mayo desactivaron el servicio que tenían de <strong>mensajería instantánea</strong> (¡como el colacao!) por <strong>jabber</strong>.</p>
<p>Mediante ese servicio de <strong>IM</strong> jabber teníamos el <strong>bot</strong> de twitter al cual podíamos:</p>
<ul>
<li>Mandar mensajes para postear en nuestro twitter</li>
<li>Recibir mensajes de nuestro <em>timeline</em> de la gente que seguíamos y teníamos marcada como <em>follow</em></li>
</ul>
<p>Es decir, ahorrarnos el tener que entrar a la puta página y tener que estar dándole a <em>f5</em> todo el rato. Para mi esto es un <strong>requisito</strong> para usar twitter. Si no es por IM, no lo usaría. </p>
<p>Estuve un tiempo en <a href="http://blaxter.jaiku.com">jaiku</a> (más que nada porque era el único servicio similar que tenía el IM activado, <a href="http://plurk.com">plurk</a>, que es molón, molón; también lo desactivó) pero ahora se ha vuelto tonto y empieza a funcionar mal. Así que pensé un poquito y dije, <em>¡leches, pero si te puedes montar un bot jabber en 4 pipas!</em>, dicho y hecho, <a href="http://twitter.com/blaxter/statuses/899569373">volví a twitter</a> creándome un bot jabber, en <a href="http://www.ruby-lang.org/es/">ruby</a>, que hace justo la misma funcionalidad que el de twitter "<em>oficial</em>" (aunque es solo para <strong>una</strong> persona obviamente, <img src='http://bicosyes.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> ). </p>
<p>Lo he llamado <strong><a href="http://github.com/blaxter/rtwittbot">RTwittBot</a></strong> (feo de cojones, lo sé), el código <a href="http://github.com/blaxter/rtwittbot">está en github</a>, para hacerlo funcionar solo necesitas tener ruby y algunas gemas que he indicado en el <em>README</em> en github. Naturalmente, necesitarás una cuenta <em>jabber</em> para que sea usada por el bot (por ejemplo cualquier cuenta que tengas de gmail sirve) aparte de la tuya propia que ya usas, todo esto se encuentra explicado en github.</p>
<p>Por ahora lo llevo usando unos días y es bastante estable, e incluso si ocurre algún fallo en el propio bot (twitter caído, bug en el código, etc...) el bot no debería caerse sino que cambia su disponibilidad a <em>away</em> e indica en su estado el porqué, para volver a cambiarlo cuando todo vuelve a la normalidad <img src='http://bicosyes.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . </p>
<p>Cualquier duda sobre su uso o lo que sea, deja un comentario <img src='http://bicosyes.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=645&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/bot-personal-jabber-para-twitter-rtwittbot/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Autocompletado e historial de métodos en la consola de ruby (irb)</title>
		<link>http://bicosyes.com/autocompletado-e-historial-de-metodos-en-la-consola-de-ruby-irb/</link>
		<comments>http://bicosyes.com/autocompletado-e-historial-de-metodos-en-la-consola-de-ruby-irb/#comments</comments>
		<pubDate>Fri, 16 May 2008 14:16:14 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[autocomplete]]></category>
		<category><![CDATA[console]]></category>
		<category><![CDATA[irb]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://bicosyes.com/autocompletado-e-historial-de-metodos-en-la-consola-de-ruby-irb/</guid>
		<description><![CDATA[Hoy le toca el turno a ruby. La consola de ruby, irb, tiene bastantes opciones de configuración, permitiendo, entre otras cosas, el autocompletado de métodos e incluso guardar un historial de comandos entre sesiones. Muy simple, simplemente añade esto a &#8230; <a href="http://bicosyes.com/autocompletado-e-historial-de-metodos-en-la-consola-de-ruby-irb/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hoy le toca el turno a <strong>ruby</strong>. La consola de ruby, <strong>irb</strong>, tiene <a href="http://www.rubycentral.com/pickaxe/irb.html">bastantes opciones</a> de configuración, permitiendo, entre otras cosas, el autocompletado de métodos e incluso guardar un historial de comandos entre sesiones. </p>
<p>Muy simple, simplemente añade esto a tu fichero ~/.irbrc (si no existe, lo creas):</p>
<pre class="ruby">equire <span style="color:#996600;">'irb/completion'</span>
&nbsp;
IRB.<span style="color:#9900CC;">conf</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:SAVE_HISTORY</span><span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#006666;">1000</span>
IRB.<span style="color:#9900CC;">conf</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:HISTORY_FILE</span><span style="color:#006600; font-weight:bold;">&#93;</span> = <span style="color:#996600;">&quot;#{ENV['HOME']}/.irb-save-history&quot;</span>
IRB.<span style="color:#9900CC;">conf</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:AUTO_INDENT</span><span style="color:#006600; font-weight:bold;">&#93;</span>  = <span style="color:#0000FF; font-weight:bold;">true</span>
IRB.<span style="color:#9900CC;">conf</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#ff3333; font-weight:bold;">:PROMPT_MODE</span><span style="color:#006600; font-weight:bold;">&#93;</span>  = <span style="color:#ff3333; font-weight:bold;">:SIMPLE</span></pre>
<p>Puedes añadir otras opciones, e incluso personalizar el <em>prompt</em> el cual lo tengo a '<em>simple</em>' porque los otros modos son demasiado informativos para mi gusto (nunca he entendido esa manía de querer incorporar siempre el número de comando en todas las consolas de los lenguajes).</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=631&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/autocompletado-e-historial-de-metodos-en-la-consola-de-ruby-irb/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Generando javascript con código ruby embebido en rails 2.x</title>
		<link>http://bicosyes.com/generando-javascript-con-codigo-ruby-embebido-en-rails-2x/</link>
		<comments>http://bicosyes.com/generando-javascript-con-codigo-ruby-embebido-en-rails-2x/#comments</comments>
		<pubDate>Sat, 03 May 2008 14:05:40 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[erb]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[rails]]></category>

		<guid isPermaLink="false">http://bicosyes.com/generando-javascript-con-codigo-ruby-embebido-en-rails-2x/</guid>
		<description><![CDATA[Hay veces que es bastante útil y cómodo devolver en una petición código javascript para que sea ejecutado en el cliente (y actualice el interfaz del usuario o lo que tenga que hacer). En vez de realizar (1) Petición, (2) &#8230; <a href="http://bicosyes.com/generando-javascript-con-codigo-ruby-embebido-en-rails-2x/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Hay veces que es bastante útil y cómodo <strong>devolver</strong> en una petición <strong>código</strong> javascript para que sea ejecutado en el cliente (y actualice el interfaz del usuario o lo que tenga que hacer). En vez de realizar <em>(1)</em> Petición, <em>(2)</em> Generar datos, <em>(3)</em> recepción y procesamiento, <em>(4)</em> actualizar página; pasamos a <em>(1)</em> Petición, <em>(2)</em> generar código, <em>(3)</em> actualizar página. Es decir nos ahorramos el parseo, además nos ahorramos tener que cargar javascript (que procesa las respuestas) en el cliente y usando <a href="http://jquery.com/">jquery</a>/<a href="http://mootools.net/">mootools</a>/* se realiza todo el proceso de forma transparente (indicando en la petición ajax que esperamos recibir un <em>script</em>). Esta técnica será válida <strong>solo</strong> para pequeñas actualizaciones (que son mayoría) y principalmente para temas de interfaz (que suelen ser triviales), pues en definitiva el código que no se ve, es código difícil de mantener.</p>
<p>En <strong>Rails</strong> tenemos <a href="http://www.codyfauser.com/2005/11/20/rails-rjs-templates"><em>templates</em> <strong>RJS</strong></a> que básicamente consiste en lo que acabo de comentar pero generando javascript con <em>wrappers</em> en vez de usar <em>js</em> sin más, algo que me parece absurdo, pero eso es otro tema. Para rails 1.2.x teníamos <a href="http://svn.danwebb.net/external/rails/plugins/minus_mor/trunk/README">este maravilloso plugin</a> de Dan Webb que te permite escribir javascript con ruby embebido en él, algo como:</p>
<pre class="ruby">&lt;% <span style="color:#0066ff; font-weight:bold;">@ids_to_modified</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> |id| %&gt;
   $<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'#'</span> + &lt;%= id %&gt;<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">removeClass</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'&lt;%= @class_to_remove %&gt;'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">highlightFade</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;
&lt;% <span style="color:#9966CC; font-weight:bold;">end</span> %&gt;</pre>
<p>Desde Rails <strong>2.x</strong> ya no es necesario el uso del plugin (en parte porque ya no va), pues podemos hacer esto mismo gracias al nuevo formato de las vistas. </p>
<p>Ahora todas las vistas tienen el formato <em>nombre.<strong>formato</strong>.<strong>template_engine</strong></em>, por ejemplo lo típico sería algo como: <em>nombre.html.erb</em>. Pero, ¿por qué no tener plantillas como <em>nombre.<strong>js</strong>.erb</em>?. De esta forma tendremos, sin incorporar plugins ni nada, la funcionalidad antes comentada, generar javascript permitiendo ruby embebido (es decir, usando <a href="http://ruby-doc.org/stdlib/libdoc/erb/rdoc/classes/ERB.html">erb</a>).</p>
<p>Para hacernos la vida algo más simple, vendría bien incorporar ciertas funciones y helpers. En tu <em>application.rb</em>, no estaría de más tener algo como:</p>
<pre class="ruby"><span style="color:#9966CC; font-weight:bold;">def</span> respond_with_js
    respond_to<span style="color:#006600; font-weight:bold;">&#123;</span>|format| <span style="color:#CC0066; font-weight:bold;">format</span>.<span style="color:#9900CC;">js</span> <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre>
<p>Por lo que nuestras acciones que vayan a ser llamadas mediante <em>xhr</em> tendrán una pinta tal que:</p>
<pre class="ruby"><span style="color:#9966CC; font-weight:bold;">def</span> vote
   <span style="color:#008000; font-style:italic;"># hacer lo que sea...</span>
   respond_with_js
<span style="color:#9966CC; font-weight:bold;">end</span></pre>
<p>Tenemos que tener en cuenta también, que el javascript generado debe de ser <strong>válido</strong> (por ejemplo escapar comillas en las cadenas, o similares). Para asegurarnos que algo es javascript válido, nada mejor que usar <em>json</em> por lo que podemos pillar prestado del plugin de <a href="http://svn.danwebb.net/external/rails/plugins/minus_mor/trunk/">MinusMOR</a> su helper (y añadirlo a <em>application_helper.rb</em>)</p>
<pre class="ruby"><span style="color:#9966CC; font-weight:bold;">def</span> js<span style="color:#006600; font-weight:bold;">&#40;</span>data<span style="color:#006600; font-weight:bold;">&#41;</span>
  <span style="color:#9966CC; font-weight:bold;">if</span> data.<span style="color:#9900CC;">respond_to</span>? <span style="color:#ff3333; font-weight:bold;">:to_json</span>
    data.<span style="color:#9900CC;">to_json</span>
  <span style="color:#9966CC; font-weight:bold;">else</span>
    data.<span style="color:#9900CC;">inspect</span>.<span style="color:#9900CC;">to_json</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre>
<p>Por lo que ahora podemos escribir cosas tal que:</p>
<pre class="ruby">$<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'div.cancel'</span><span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">append</span><span style="color:#006600; font-weight:bold;">&#40;</span>
    &lt;%=js link_to<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#996600;">'Cancelar'</span>, <span style="color:#ff3333; font-weight:bold;">:action</span> =&gt; <span style="color:#996600;">'cancel'</span><span style="color:#006600; font-weight:bold;">&#41;</span> %&gt;
<span style="color:#006600; font-weight:bold;">&#41;</span>;
<span style="color:#008000; font-style:italic;"># o</span>
alert<span style="color:#006600; font-weight:bold;">&#40;</span>&lt;%=js error_message_for<span style="color:#006600; font-weight:bold;">&#40;</span>@error<span style="color:#006600; font-weight:bold;">&#41;</span> %&gt;<span style="color:#006600; font-weight:bold;">&#41;</span>;</pre>
<p>Finalmente, si queremos usar <em>partial's</em> tendremos que añadir este helper para soportar el nuevo formato de las plantillas (gracias a <a href="http://mad.ly/2007/11/02/javascript-embedded-ruby-templates-with-rails-out-of-the-box/">mad.ly</a>):</p>
<pre class="ruby"><span style="color:#9966CC; font-weight:bold;">def</span> partial<span style="color:#006600; font-weight:bold;">&#40;</span>name, 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>
  old_format = <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">template_format</span>
  <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">template_format</span> = <span style="color:#ff3333; font-weight:bold;">:html</span>
  js render<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#ff3333; font-weight:bold;">:partial</span> =&gt; name <span style="color:#006600; font-weight:bold;">&#125;</span>.<span style="color:#9900CC;">merge</span><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>
<span style="color:#9966CC; font-weight:bold;">ensure</span>
  <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">template_format</span> = old_format
<span style="color:#9966CC; font-weight:bold;">end</span></pre>
<p>Fíjate que no estamos sobreescribiendo el <em>render :partial</em> típico, es un helper simplemente. Para usarlo tendríamos que hacer algo como:</p>
<pre>$('#some_div').html(&lt;%=partial 'movie_information', :object =&gt; @movie %&gt;);</pre>
<p>En definitiva una forma mucho más cómoda, potente y simple de generar javascript desde el lado del servidor. Aunque insisto en que solo se debería de usar esta táctica para cosas triviales y pequeñas.</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=627&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/generando-javascript-con-codigo-ruby-embebido-en-rails-2x/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Comparando reales sin terminos naturales</title>
		<link>http://bicosyes.com/comparando-reales-sin-terminos-naturales/</link>
		<comments>http://bicosyes.com/comparando-reales-sin-terminos-naturales/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 18:52:55 +0000</pubDate>
		<dc:creator>blaxter</dc:creator>
				<category><![CDATA[Programación]]></category>
		<category><![CDATA[float]]></category>
		<category><![CDATA[float point]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://bicosyes.com/comparando-reales-sin-terminos-naturales/</guid>
		<description><![CDATA[Lo sé, el título no tiene mucho sentido, pero quería hacer una rima. Veamos una pequeña sesión en la consola de ruby &#160; &#62;&#62; value = 69.99 =&#62; 69.99 &#62;&#62; value * 100 =&#62; 6999.0 &#62;&#62; value * 100 == &#8230; <a href="http://bicosyes.com/comparando-reales-sin-terminos-naturales/">Sigue leyendo <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lo sé, el título no tiene mucho sentido, pero quería hacer una rima. Veamos una pequeña sesión en la consola de ruby</p>
<pre class="ruby">&nbsp;
&gt;&gt; value = <span style="color:#006666;">69.99</span>
=&gt; <span style="color:#006666;">69.99</span>
&gt;&gt; value * <span style="color:#006666;">100</span>
=&gt; <span style="color:#006666;">6999.0</span>
&gt;&gt; value * <span style="color:#006666;">100</span> == <span style="color:#006666;">6999.0</span>
=&gt; <span style="color:#0000FF; font-weight:bold;">false</span>
&gt;&gt; a = value * <span style="color:#006666;">100</span>
=&gt; <span style="color:#006666;">6999.0</span>
&gt;&gt; b = <span style="color:#006666;">6999.0</span>
=&gt; <span style="color:#006666;">6999.0</span>
&gt;&gt; a.<span style="color:#9966CC; font-weight:bold;">class</span> == b.<span style="color:#9966CC; font-weight:bold;">class</span> &amp;&amp; a.<span style="color:#9900CC;">is_a</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0066; font-weight:bold;">Float</span><span style="color:#006600; font-weight:bold;">&#41;</span>
=&gt; <span style="color:#0000FF; font-weight:bold;">true</span>
&gt;&gt; <span style="color:#CC0066; font-weight:bold;">print</span> <span style="color:#996600;">&quot;#{a} es distinto a #{b} obviamente&quot;</span> <span style="color:#9966CC; font-weight:bold;">unless</span> a == b
<span style="color:#006666;">6999.0</span> es distinto a <span style="color:#006666;">6999.0</span> obviamente
&gt;&gt; a.<span style="color:#9900CC;">floor</span>
=&gt; <span style="color:#006666;">6998</span></pre>
<p>Nada fuera de lo normal, ¿no?. ¿O si?.</p>
<img src="http://bicosyes.com/?ak_action=api_record_view&id=624&type=feed" alt="" />]]></content:encoded>
			<wfw:commentRss>http://bicosyes.com/comparando-reales-sin-terminos-naturales/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

