<?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>def Tenako.blog () end &#187; ruby</title>
	<atom:link href="http://blog.tenako.com/tag/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tenako.com</link>
	<description></description>
	<lastBuildDate>Thu, 12 Aug 2010 19:26:01 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Ruby: Expirar los mensajes de Starling en 3 comodos pasos</title>
		<link>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/</link>
		<comments>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/#comments</comments>
		<pubDate>Fri, 20 Mar 2009 17:12:12 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[Add new tag]]></category>
		<category><![CDATA[expiry]]></category>
		<category><![CDATA[starling]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=113</guid>
		<description><![CDATA[Si te pasa como a mi, que quieres almacenar mensajes en el starling pero que algunos de ellos lleven &#8220;fecha de caducidad&#8220;, sigue los siguiente pasos. Paso 1 : Abrir en un editor el fichero handler.rb perteneciente a la gema starling-starling. Paso 2 : En el método Handler#set_data añadir la siguiente linea justo antes de [...]]]></description>
			<content:encoded><![CDATA[<p>Si te pasa como a mi, que quieres almacenar mensajes en el starling pero que algunos de ellos lleven &#8220;<a href="http://www.deveiate.org/code/Ruby-MemCache/classes/MemCache.html#M000009" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.deveiate.org');">fecha de caducidad</a>&#8220;, sigue los siguiente pasos.</p>
<ul>
<li><strong>Paso 1 :</strong> Abrir en un editor el fichero handler.rb perteneciente a la gema <a href="http://github.com/starling/starling/tree/master" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');">starling-starling</a>.</li>
<li><strong>Paso 2 :</strong> En el método <em>Handler#set_data</em> añadir la siguiente linea justo antes de hacer el pack para generar la variable <em>internal_data</em>.</li>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  ...
  <span style="color:#9900CC;">expiry</span> = <span style="color:#CC00FF; font-weight:bold;">Time</span>.<span style="color:#9900CC;">now</span>.<span style="color:#9900CC;">to_i</span> <span style="color:#006600; font-weight:bold;">+</span> expiry.<span style="color:#9900CC;">to_i</span> <span style="color:#9966CC; font-weight:bold;">unless</span> expiry.<span style="color:#9900CC;">to_i</span> == 0
  ...</pre></div></div>

<li><strong>Paso 3 :</strong> Guarda y re-arranca el starling.Todo debería de ir como la seda.</li>
</ul>
<p>Con esto, lo único que hemos hecho es corregir un pequeño bug que hay en <em>Handler#get</em> ya que en este método solo se devuelve un mensaje si su expiry es 0 o si expiry es mayor que now (now en este contexto es Time.now.to_i ). El fallo viene de comparar a now (valor <a href="http://en.wikipedia.org/wiki/Unix_time" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">unix time</a>) con expiry el cual es solo un offset desde el momento en el que decidimos guardar un mensaje en starling.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">  ...
  <span style="color:#9966CC; font-weight:bold;">break</span> <span style="color:#9966CC; font-weight:bold;">if</span> expiry == 0 || expiry <span style="color:#006600; font-weight:bold;">&gt;</span>= now
&nbsp;
  <span style="color:#0066ff; font-weight:bold;">@expiry_stats</span><span style="color:#006600; font-weight:bold;">&#91;</span>key<span style="color:#006600; font-weight:bold;">&#93;</span> <span style="color:#006600; font-weight:bold;">+</span>= <span style="color:#006666;">1</span>
  expiry, data = <span style="color:#0000FF; font-weight:bold;">nil</span>
  ...</pre></div></div>

<p>Con la linea que añadimos al método <em>Handler#set_data</em> forzamos que la comparación sea entre dos valores unix time.Uno refiriéndose al momento actual (now) y otro al momento en el que expirara el mensaje (la suma de Time.now.to_i en el momento del almacenarlo y el tiempo de vida del mensaje).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2009/03/20/expirar-mensajes-starling/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ruby,Rails: &#8220;metodos encadenados&#8221;</title>
		<link>http://blog.tenako.com/2008/09/19/rubyrails-metodos-encadenados/</link>
		<comments>http://blog.tenako.com/2008/09/19/rubyrails-metodos-encadenados/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 16:13:15 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[cadena]]></category>
		<category><![CDATA[metodos]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=7</guid>
		<description><![CDATA[Una de las cosas que mas me gustan de Ruby es su dinamismo y la posibilidad de &#8220;abrir&#8221; las clases y modulos para añadir o redefinir metodos totalmente dinamicamente y en tiempo de ejecucion. Esta funcionalidad junto con la posibilidad de saber cuando un modulo ha sido incluido en una clase nos permite añadir funcionalidad [...]]]></description>
			<content:encoded><![CDATA[<p>Una de las cosas que mas me gustan de <a href="http://www.ruby-lang.org/es/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-lang.org');" target="_blank">Ruby</a> es su dinamismo y la posibilidad de &#8220;abrir&#8221; las clases y modulos para añadir o redefinir metodos totalmente dinamicamente y en tiempo de ejecucion.</p>
<p>Esta funcionalidad junto con la posibilidad de saber cuando un modulo ha sido incluido en una clase nos permite añadir funcionalidad a las clases que incluyen el modulo sin que estan tengan que percibirlo.</p>
<p>Un ejemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#9966CC; font-weight:bold;">Module</span>
  <span style="color:#9966CC; font-weight:bold;">def</span> included<span style="color:#006600; font-weight:bold;">&#40;</span>base<span style="color:#006600; font-weight:bold;">&#41;</span>
    <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Included module &quot;</span> <span style="color:#006600; font-weight:bold;">+</span> name
&nbsp;
    without = <span style="color:#996600;">&quot;test_method_#{name}_without_filters&quot;</span>.<span style="color:#9900CC;">to_sym</span>
    with =<span style="color:#996600;">&quot;test_method_#{name}_with_filters&quot;</span>.<span style="color:#9900CC;">to_sym</span>
    base.<span style="color:#9900CC;">class_eval</span> <span style="color:#9966CC; font-weight:bold;">do</span>
      alias_method without, <span style="color:#ff3333; font-weight:bold;">:test_method</span>
      alias_method <span style="color:#ff3333; font-weight:bold;">:test_method</span>, with
    <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Lo que he hecho es redefinir el metodo <a href="http://www.ruby-doc.org/core/classes/Module.html#M001683" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">included</a> para que todos los modulos indiquen que ha sido incluidos y que hagan un alias sobre el metodo &#8220;<em>test_method</em>&#8220;.</p>
<blockquote><p>Hay que tener en cuenta que <a href="http://www.ruby-doc.org/core/classes/Module.html#M001676" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">alias_method</a> no sobreescribe el metodo original, sino que hace una guarda una referencia a este, de forma que aun pueda ser invocado.</p></blockquote>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">module</span> A
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> test_method_A_with_filters
    <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Doing something really important in module A&quot;</span>
    test_method_A_without_filters
  <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;">module</span> B
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> test_method_B_with_filters
    <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Doing something really important in module B&quot;</span>
    test_method_B_without_filters
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
&nbsp;
<span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#CC00FF; font-weight:bold;">Test</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">def</span> test_method
      <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Inside method of class A&quot;</span>
&nbsp;
      <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Backtrace:&quot;</span>
      <span style="color:#CC0066; font-weight:bold;">caller</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> |text| <span style="color:#CC0066; font-weight:bold;">p</span> text <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#0000FF; font-weight:bold;">return</span>
  <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
  <span style="color:#9966CC; font-weight:bold;">include</span> A
  <span style="color:#9966CC; font-weight:bold;">include</span> B
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Creamos los modulos, la clase e incluimos los primeros en dicha clase.Hasta aqui nada nuevo bajo el sol.</p>
<p>Probemos entonces el codigo en irb,</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">madtrick:~<span style="color: #000000; font-weight: bold;">/</span>programacion<span style="color: #000000; font-weight: bold;">/</span>ruby madtrick$ irb
irb<span style="color: #7a0874; font-weight: bold;">&#40;</span>main<span style="color: #7a0874; font-weight: bold;">&#41;</span>:001:0<span style="color: #000000; font-weight: bold;">&gt;</span> require <span style="color: #ff0000;">&quot;test30&quot;</span>
<span style="color: #ff0000;">&quot;Included module A&quot;</span>
<span style="color: #ff0000;">&quot;Included module B&quot;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
&nbsp;
irb<span style="color: #7a0874; font-weight: bold;">&#40;</span>main<span style="color: #7a0874; font-weight: bold;">&#41;</span>:002:0<span style="color: #000000; font-weight: bold;">&gt;</span> Test.new.test_method
<span style="color: #ff0000;">&quot;Doing something really important in module B&quot;</span>
<span style="color: #ff0000;">&quot;Doing something really important in module A&quot;</span>
<span style="color: #ff0000;">&quot;Inside method of class A&quot;</span>
&nbsp;
<span style="color: #ff0000;">&quot;Backtrace:&quot;</span>
<span style="color: #ff0000;">&quot;./test30.rb:14:in `test_method_B_without_filters'&quot;</span>
<span style="color: #ff0000;">&quot;./test30.rb:32:in `test_method'&quot;</span>
<span style="color: #ff0000;">&quot;(irb):2:in `irb_binding'&quot;</span>
<span style="color: #ff0000;">&quot;/opt/local/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'&quot;</span>
<span style="color: #ff0000;">&quot;:0&quot;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> nil</pre></div></div>

<p>Si hechamos un vistazo a la salida generada en irb,</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">irb<span style="color: #7a0874; font-weight: bold;">&#40;</span>main<span style="color: #7a0874; font-weight: bold;">&#41;</span>:001:0<span style="color: #000000; font-weight: bold;">&gt;</span> require <span style="color: #ff0000;">&quot;test30&quot;</span>
<span style="color: #ff0000;">&quot;Included module A&quot;</span>
<span style="color: #ff0000;">&quot;Included module B&quot;</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #c20cb9; font-weight: bold;">true</span></pre></div></div>

<p>Los modulos se incluyen en la clase en el orden deseado</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">irb<span style="color:#006600; font-weight:bold;">&#40;</span>main<span style="color:#006600; font-weight:bold;">&#41;</span>:002:0<span style="color:#006600; font-weight:bold;">&gt;</span> <span style="color:#CC00FF; font-weight:bold;">Test</span>.<span style="color:#9900CC;">new</span>.<span style="color:#9900CC;">test_method</span>
<span style="color:#996600;">&quot;Doing something really important in module B&quot;</span>
<span style="color:#996600;">&quot;Doing something really important in module A&quot;</span>
<span style="color:#996600;">&quot;Inside method of class A&quot;</span></pre></div></div>

<p>Ahora creamos un objeto de tipo Test e invocamos sobre él el metodo &#8220;test_method&#8221;&#8230;!Pero que ha pasado aqui¡!De donde salen esa lineas¡No no pongamos nerviosos y averigüemos que pasa.</p>
<p>Cuando redefinimos el metodo <em>included</em> de la clase module, realizamos unos alias.<br />
Para el modulo A:</p>
<ul>
<li><strong>Nuevo nombre</strong> : test_method_A_without_filters,<strong>nombre antiguo</strong>: test_method</li>
<li><strong>Nuevo nombre</strong> : test_method, <strong>nombre_antiguo</strong> test_method_A_with_filters</li>
</ul>
<p>Para el modulo B , lo mismo pero cambiando la A por una B.</p>
<p>El resultado de estos alias es el que vemos en la salida de irb, al invocar sobre un objeto de la clase Test<br />
su metodo de instancia &#8220;test_method&#8221; lo primero que vemos no es &#8220;<em>Inside method of class A</em>&#8221; sino &#8220;<em>Doing something really important in module B</em>&#8220;,seguido de un &#8220;<em>Doing something really important in module A</em>&#8221; para finalmente ver nuestro esperado &#8220;<em>Inside method of class A</em>&#8220;,esto es asi porque:</p>
<ol>
<li>El ultimo modulo incluido fue el B, por tanto su alias &#8220;sobreescribioo&#8221; al creado por el modulo A.Es decir al hacer Test.new.test_method en realidad estamos invocando a test_method_B_with_filters</li>
<li>Tras ejecutar este metodo, invocamos al metodo &#8220;original&#8221;, que en este caso no es el definido en la clase, sino el alias realizado por el modulo A</li>
<li>Tras ejecutar este ultimo alias, volvemos a invocar al metodo original (alias de  &#8220;test_method_A_without_filters&#8221;) quien finalmente si que es el metodo de la clase Test</li>
</ol>
<p>Utilizando <a href="http://www.ruby-doc.org/core/classes/Kernel.html#M005955" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">caller</a> podemos saber la <a href="http://en.wikipedia.org/wiki/Stack_trace" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');" target="_blank">stacktrace</a> de nuestro programa y asi saber cual fue la direccion de los mensajes.Esto lo podemos ver en este trozo de la salida de irb,</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #ff0000;">&quot;Backtrace:&quot;</span>
<span style="color: #ff0000;">&quot;./test30.rb:19:in `test_method_B_without_filters'&quot;</span>
<span style="color: #ff0000;">&quot;./test30.rb:30:in `test_method'&quot;</span>
<span style="color: #ff0000;">&quot;(irb):2:in `irb_binding'&quot;</span>
<span style="color: #ff0000;">&quot;/opt/local/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'&quot;</span>
<span style="color: #ff0000;">&quot;:0&quot;</span></pre></div></div>

<p>Teniendo en cuenta que las primeras lineas indican los ultimos mensajes.Tenemos que:</p>
<p>En la linea 30 vamos enviar un mensaje tras recibir uno con destino a &#8220;<em>test_method</em>&#8221; alias de &#8220;<em>test_method_B_with_filters</em>&#8220;,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>28
29
30
31
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">  <span style="color:#9966CC; font-weight:bold;">def</span> test_method_B_with_filters
    <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Doing something really important in module B&quot;</span>
    test_method_B_without_filters
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>En la linea 19 vamos a enviar un mensaje tras recibir uno con destino &#8220;<em>test_method_B_without_filters</em>&#8221;<br />
el cual es un alias de &#8220;<em>test_method</em>&#8220;,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>17
18
19
20
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;"> <span style="color:#9966CC; font-weight:bold;">def</span> test_method_A_with_filters
    <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;Doing something really important in module A&quot;</span>
    test_method_A_without_filters
  <span style="color:#9966CC; font-weight:bold;">end</span></pre></td></tr></table></div>

<p>Como se puede apreciar es una forma bastante sencilla de añadir funcionalidad sin influir para nada en las clases.Y de aqui es de donde saque el titulo, porque literalmente estamos encadenando metodos.</p>
<p><strong>Para terminar</strong><br />
Si alguien le extraña la coletilla _filters que utilize para hacer los alias , tiene su explicacion.Ultimamente estoy curioseando en el codigo de <a href="http://www.rubyonrails.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.rubyonrails.org');" target="_blank">Rails</a>, y para poder seguir un orden me voy guiando por el orden el que se procesan las peticiones ,gracias al debugger para webrick y otros servidores.Bueno la cosa es que llegue al fichero <a href="http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/filters.rb" onclick="javascript:pageTracker._trackPageview('/outbound/article/github.com');">filters.rb</a>  donde me encontre con este codigo,</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"> <span style="color:#9966CC; font-weight:bold;">module</span> InstanceMethods <span style="color:#008000; font-style:italic;"># :nodoc:</span>
      <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">included</span><span style="color:#006600; font-weight:bold;">&#40;</span>base<span style="color:#006600; font-weight:bold;">&#41;</span>
        base.<span style="color:#9900CC;">class_eval</span> <span style="color:#9966CC; font-weight:bold;">do</span>
          alias_method_chain <span style="color:#ff3333; font-weight:bold;">:perform_action</span>, <span style="color:#ff3333; font-weight:bold;">:filters</span>
          alias_method_chain <span style="color:#ff3333; font-weight:bold;">:process</span>, <span style="color:#ff3333; font-weight:bold;">:filters</span>
        <span style="color:#9966CC; font-weight:bold;">end</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
...</pre></div></div>

<p>¿alias_method_chain?, no me sonaba para nada, asi que tras una consulta a google llegue a <a href="http://weblog.rubyonrails.org/2006/4/26/new-in-rails-module-alias_method_chain" onclick="javascript:pageTracker._trackPageview('/outbound/article/weblog.rubyonrails.org');">esto</a>:</p>
<blockquote><p>All over the internals of Rails you’ll find code like this in a module: </p>
<p>  module Layout #:nodoc:<br />
    def self.included(base)<br />
      base.extend(ClassMethods)<br />
      base.class_eval do<br />
        alias_method :render_with_no_layout, :render<br />
        alias_method :render, :render_with_a_layout<br />
        # &#8230; etc<br />
This makes it so that when the module is included into the base class, it adds behavior onto some method in that class without the method having to be aware of the fact that it’s being enhanced</p></blockquote>
<p>En resumidas cuentas, que <em>alias_method_chain</em> hace lo que acabos de hacer nosotros pero un poquillo mejor ya que se puede aplicar a cualquier metodo, no solo a <em>test_method</em> como en nuestro caso.</p>
<p>Volviendo a lo de la coletilla _filters, la explicacion es que donde vi el primer ejemplo de alias_method_chain fue en el codigo indicado arriba y entonces fue lo primero que se me ocurrio.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/09/19/rubyrails-metodos-encadenados/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
