<?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; rails</title>
	<atom:link href="http://blog.tenako.com/category/programacion/rails-programacion/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tenako.com</link>
	<description></description>
	<lastBuildDate>Mon, 19 Jul 2010 17:32: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>Rails: Observar un modelo desde un plugin == problemas</title>
		<link>http://blog.tenako.com/2008/11/16/rails-observar-un-modelo-desde-un-plugin-problemas/</link>
		<comments>http://blog.tenako.com/2008/11/16/rails-observar-un-modelo-desde-un-plugin-problemas/#comments</comments>
		<pubDate>Sun, 16 Nov 2008 23:52:35 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[desarrollo]]></category>
		<category><![CDATA[observers]]></category>
		<category><![CDATA[plugin]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=46</guid>
		<description><![CDATA[Rails implementa el patron observador para permitir observar un modelo y responder así los diferentes estados que puede atravesar un objeto de dicho modelo.
Actualmente estoy trabajando en un proyecto donde es necesario que dos aplicaciones realizadas  en Rails se comuniquen entre si mediante mediante Rest.Para conseguir esto, una de las aplicaciones incluye un plugin [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.rubyonrails.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.rubyonrails.org');">Rails</a> <a href="http://api.rubyonrails.org/classes/ActiveRecord/Observer.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.rubyonrails.org');">implementa</a> el <a href="http://en.wikipedia.org/wiki/Observer_pattern" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">patron observador</a> para permitir observar un modelo y responder así los diferentes estados que puede atravesar un objeto de dicho modelo.</p>
<p>Actualmente estoy trabajando en un proyecto donde es necesario que dos aplicaciones realizadas  en Rails se comuniquen entre si mediante mediante <a href="http://en.wikipedia.org/wiki/Representational_State_Transfer" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">Rest</a>.Para conseguir esto, una de las aplicaciones incluye un plugin (proxy) en la otra.En este plugin se encarga de lo siguiente:</p>
<ul>
<li> Se definen los datos necesarios para esta comunicacion entre aplicaciones como así requiere <a href="http://api.rubyonrails.org/classes/ActiveResource/Base.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.rubyonrails.org');">ActiveResource::Base</a></li>
<li>Se registra un observador que observara (valga la redundancia)  uno de los modelos en la aplicación receptora el plugin</li>
</ul>
<p>Antes de continuar con este post, tengo que confesar una cosilla, observar un modelo desde un plugin es un problema, si y solo si  se hace en modo <strong>desarrollo</strong>.¿Y por qué?</p>
<p>Si no te interesa saber el porque de los problemas y has llegado hasta aqui buscando una solucion, con indicar a Rails que recargue los plugins en cada petición tendrás el asunto resuelto.</p>
<p>Para ello sigue los siguientes pasos:</p>
<p><strong>1º. Indicar a Rails que quieres recargar los plugins</strong></p>
<p>En <strong>config/environment.rb</strong> añade esta linea:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">config.<span style="color:#9900CC;">reload_plugins</span> = <span style="color:#0000FF; font-weight:bold;">true</span></pre></div></div>

<p>Con esto lo único que hacemos en realidad, es evitar que el path /lib de cada plugin sea incluido en <strong>Dependencies.load_once_paths</strong></p>
<p>Pero esto puede que no nos arregle nuestro problema y para muestra un ejemplo:</p>
<p>Arrancare el <a href="http://www.webrick.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.webrick.org');">webrick</a> en modo debug con un breakpoint en el método dispatch del fichero dispatcher.rb, método invocado para cada petición.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> dispatch<span style="color:#006600; font-weight:bold;">&#40;</span>cgi = <span style="color:#0000FF; font-weight:bold;">nil</span>, session_options = <span style="color:#6666ff; font-weight:bold;">CgiRequest::DEFAULT_SESSION_OPTIONS</span>, output = <span style="color:#ff6633; font-weight:bold;">$stdout</span><span style="color:#006600; font-weight:bold;">&#41;</span>
    debugger
    new<span style="color:#006600; font-weight:bold;">&#40;</span>output<span style="color:#006600; font-weight:bold;">&#41;</span>.<span style="color:#9900CC;">dispatch_cgi</span><span style="color:#006600; font-weight:bold;">&#40;</span>cgi, session_options<span style="color:#006600; font-weight:bold;">&#41;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Arrancamos y enviamos una peticion:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">=<span style="color: #000000; font-weight: bold;">&gt;</span> Booting WEBrick...
=<span style="color: #000000; font-weight: bold;">&gt;</span> Debugger enabled
=<span style="color: #000000; font-weight: bold;">&gt;</span> Rails 2.1.1 application started on http:<span style="color: #000000; font-weight: bold;">//</span>events.trabenet.local:<span style="color: #000000;">3001</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> Ctrl-C to shutdown server; call with <span style="color: #660033;">--help</span> <span style="color: #000000; font-weight: bold;">for</span> options
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">16</span> <span style="color: #000000;">21</span>:<span style="color: #000000;">37</span>:<span style="color: #000000;">24</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  WEBrick 1.3.1
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">16</span> <span style="color: #000000;">21</span>:<span style="color: #000000;">37</span>:<span style="color: #000000;">24</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  ruby 1.8.7 <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">2008</span>-08-08<span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>i686-darwin8<span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">16</span> <span style="color: #000000;">21</span>:<span style="color: #000000;">37</span>:<span style="color: #000000;">25</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  WEBrick::HTTPServer<span style="color: #666666; font-style: italic;">#start: pid=1394 port=3001</span>
<span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>actionpack-2.1.1<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>action_controller<span style="color: #000000; font-weight: bold;">/</span>dispatcher.rb:<span style="color: #000000;">36</span>
new<span style="color: #7a0874; font-weight: bold;">&#40;</span>output<span style="color: #7a0874; font-weight: bold;">&#41;</span>.dispatch_cgi<span style="color: #7a0874; font-weight: bold;">&#40;</span>cgi, session_options<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>El plugin del que tratamos declara una constante, EventObserver. Veamos si existe:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> EventObserver
EventObserver
<span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> EventObserver.object_id
<span style="color: #000000;">25840630</span></pre></div></div>

<p>Perfecto.</p>
<p>Como en mi config/environment.rb indico que quiere recargar mis plugins, tenemos que:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> Dependencies.load_once_paths
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span></pre></div></div>

<p>Y los load_paths son:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"><span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> pp Dependencies.load_paths
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/app/controllers/&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/app&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/app/models&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/app/controllers&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/app/helpers&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/config&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor&quot;</span>,
 <span style="color: #ff0000;">&quot;/opt/local/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/../builtin/rails_info/&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/background/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/localization-with-gettext/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/localized_url_helpers/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/opt/local/lib/ruby/gems/1.8/gems/mbleigh-acts-as-taggable-on-1.0.2/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/thinking-sphinx/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/trabenet-auth/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/trabenet-core/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/trabenet-people-proxy/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/Users/madtrick/programacion/trabesoluciones/trabenet-sources/trabenet-events/vendor/plugins/trabenet_subscriptions_proxy/lib&quot;</span>,
 <span style="color: #ff0000;">&quot;/opt/local/lib/ruby/gems/1.8/gems/will_paginate-2.2.2/lib&quot;</span><span style="color: #7a0874; font-weight: bold;">&#93;</span></pre></div></div>

<p>Por tanto en cada nueva petición los plugins serán candidatos a ser recargados.</p>
<p>Veamos si esto es así con otra petición:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">127.0.0.1 - - <span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">16</span><span style="color: #000000; font-weight: bold;">/</span>Nov<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">2008</span>:<span style="color: #000000;">22</span>:00:<span style="color: #000000;">21</span> CET<span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #ff0000;">&quot;POST /events.xml HTTP/1.1&quot;</span> <span style="color: #000000;">201</span> <span style="color: #000000;">1</span>
- -<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>events.xml
<span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>actionpack-2.1.1<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>action_controller<span style="color: #000000; font-weight: bold;">/</span>dispatcher.rb:<span style="color: #000000;">36</span>
new<span style="color: #7a0874; font-weight: bold;">&#40;</span>output<span style="color: #7a0874; font-weight: bold;">&#41;</span>.dispatch_cgi<span style="color: #7a0874; font-weight: bold;">&#40;</span>cgi, session_options<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">11</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> EventObserver.object_id
<span style="color: #000000;">25840630</span></pre></div></div>

<p>Pues no, aquí no se recarga nada!! porque como podemos apreciar , el object_id de la constante es el mismo que el de la primera petición, es decir son el mismo objeto.</p>
<p><a href="http://blog.tenako.com/wp-content/uploads/2008/11/zpatontao.jpg" ><img src="http://blog.tenako.com/wp-content/uploads/2008/11/zpatontao-270x300.jpg" alt="" title="zpatontao" width="270" height="300" class="aligncenter size-medium wp-image-48" /></a></p>
<p><strong>2º.Segundo paso de la solución,descargar las constantes del entorno</strong></p>
<p>La explicación a que el objeto representado por EventObserver sea el mismo esto es la siguiente:</p>
<p>Para empezar hay que tener en cuanta que para que una constante definida en un plugin tenga validez en Rails es necesario que ocurra una de las siguientes posibilidades:</p>
<ul>
<li>Cuando se inicializa el entorno de Rails, para cada plugin se evalúa su fichero <strong>init.rb</strong> de forma que podemos utilizar llamadas a <em>require</em> para incluir el código  contenido en el directorio /lib del plugin (y por tanto las constantes de este), en Rails.
</li>
<li>Que las constantes sean cargadas de forma dinámica como ya explique en <a href="http://blog.tenako.com/2008/11/14/rails-carga-dinamica-de-constantes/" >este post</a>, de forma que cada una de estas constantes incluidas de esta forma pasa a formar parte del array <strong>Dependencies.autoloaded_constants</strong>.Esto ultimo es importante.</li>
</ul>
<p>La importancia de la forma en la que se carga una constante en Rails, reside en <strong>que</strong> es lo que se <strong>recarga</strong> en cada petición y que es lo que se <strong>descarga</strong> tras cada peticion.Tras cada petición (si estamos en modo de desarrollo) se enviara un mensaje a <strong>Dependencies.clear</strong>.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> clear
      log_call
      loaded.<span style="color:#9900CC;">clear</span>
      remove_unloadable_constants!
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>La parte interesante de Dependencies.clear es la llamada al método <strong>remove_unloadable_constants!</strong></p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> remove_unloadable_constants!
      autoloaded_constants.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |const| remove_constant const <span style="color:#006600; font-weight:bold;">&#125;</span>
      autoloaded_constants.<span style="color:#9900CC;">clear</span>
      explicitly_unloadable_constants.<span style="color:#9900CC;">each</span> <span style="color:#006600; font-weight:bold;">&#123;</span> |const| remove_constant const <span style="color:#006600; font-weight:bold;">&#125;</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>En este método se borra la constante indicada del modulo o clase correspondiente. Como se puede apreciar se borraran tanto las constante &#8220;autocargadas&#8221; como las indicadas explicitaménte en <strong>Dependencies.explicitly_unloadable_constants</strong>.</p>
<p>A pesar de haber indicado en nuestro environment.rb que queríamos recargar los plugins (config.reload_plugins=true); para cada petición no se volverá a evaluar el fichero init.rb de cada plugin y  por tanto, si nuestras constantes se cargan en Rails mediante llamadas a <strong>require</strong> (no existirán en el array Dependencies.autoloaded_constants) ; estas no volverán a ser cargadas debido a  que no habrá necesidad de ello al no haber sido descargadas en Dependencies.explicitly_unloadable_constants.Para solucionar esto podemos optar por una de estas opciones:</p>
<ul>
<li>No utilizar requires y dejar la carga de las constantes en manos de los mecanismos de Rails</li>
<li>Hacer uso de Depedencies.explicitly_unloadable_constants, indicando en dicho array las constantes que queremos que se descarguen tras cada petición</li>
</ul>
<p>Volviendo a nuestro ejemplo, probemos una de estas opciones.Utilizaremos Depedencies.explicitly_unloadable_constants.</p>
<p>En mi caso, defino las constantes que quiero que se descargen en el init.rb del plugin (por eso de tener todo juntito : ) ).</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">Dependencies.<span style="color:#9900CC;">explicitly_unloadable_constants</span> = <span style="color:#996600;">'EventObserver'</span></pre></div></div>

<p>Y lo probamos de nuevo con webrick:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">=<span style="color: #000000; font-weight: bold;">&gt;</span> Booting WEBrick...
=<span style="color: #000000; font-weight: bold;">&gt;</span> Debugger enabled
=<span style="color: #000000; font-weight: bold;">&gt;</span> Rails 2.1.1 application started on http:<span style="color: #000000; font-weight: bold;">//</span>events.trabenet.local:<span style="color: #000000;">3001</span>
=<span style="color: #000000; font-weight: bold;">&gt;</span> Ctrl-C to shutdown server; call with <span style="color: #660033;">--help</span> <span style="color: #000000; font-weight: bold;">for</span> options
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">17</span> 00:01:<span style="color: #000000;">15</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  WEBrick 1.3.1
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">17</span> 00:01:<span style="color: #000000;">15</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  ruby 1.8.7 <span style="color: #7a0874; font-weight: bold;">&#40;</span><span style="color: #000000;">2008</span>-08-08<span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>i686-darwin8<span style="color: #7a0874; font-weight: bold;">&#93;</span>
<span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">2008</span>-<span style="color: #000000;">11</span>-<span style="color: #000000;">17</span> 00:01:<span style="color: #000000;">15</span><span style="color: #7a0874; font-weight: bold;">&#93;</span> INFO  WEBrick::HTTPServer<span style="color: #666666; font-style: italic;">#start: pid=1442 port=3001</span>
<span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>actionpack-2.1.1<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>action_controller<span style="color: #000000; font-weight: bold;">/</span>dispatcher.rb:<span style="color: #000000;">36</span>
new<span style="color: #7a0874; font-weight: bold;">&#40;</span>output<span style="color: #7a0874; font-weight: bold;">&#41;</span>.dispatch_cgi<span style="color: #7a0874; font-weight: bold;">&#40;</span>cgi, session_options<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">2</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> EventObserver.object_id
<span style="color: #000000;">25840560</span></pre></div></div>

<p>Lanzamos otra petición.</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">127.0.0.1 - - <span style="color: #7a0874; font-weight: bold;">&#91;</span><span style="color: #000000;">17</span><span style="color: #000000; font-weight: bold;">/</span>Nov<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">2008</span>:00:01:<span style="color: #000000;">17</span> CET<span style="color: #7a0874; font-weight: bold;">&#93;</span> <span style="color: #ff0000;">&quot;POST /events.xml HTTP/1.1&quot;</span> <span style="color: #000000;">201</span> <span style="color: #000000;">1</span>
- -<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #000000; font-weight: bold;">/</span>events.xml
<span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>actionpack-2.1.1<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>action_controller<span style="color: #000000; font-weight: bold;">/</span>dispatcher.rb:<span style="color: #000000;">36</span>
new<span style="color: #7a0874; font-weight: bold;">&#40;</span>output<span style="color: #7a0874; font-weight: bold;">&#41;</span>.dispatch_cgi<span style="color: #7a0874; font-weight: bold;">&#40;</span>cgi, session_options<span style="color: #7a0874; font-weight: bold;">&#41;</span>
<span style="color: #7a0874; font-weight: bold;">&#40;</span>rdb:<span style="color: #000000;">11</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> EventObserver.object_id
<span style="color: #000000;">27418300</span></pre></div></div>

<p>Como se puede apreciar en esta ocasión son objetos distintos y por tanto realmente se recargado la constante.</p>
<p>Tras hacer esto, ya podemos observar con tranquilidad a nuestros modelos desde el plugin.</p>
<p>A partir de aquí voy a explicar el porque de la necesidad de recargar el contenido de nuestros plugins para poder observar a un modelo en modo de desarrollo.</p>
<p>Como explique antes, si no se recarga el contenido de nuestros plugins y en concreto la clase donde definimos el observador del modelo, tendremos un problema.¿Y por qué?</p>
<p>Primero , algunas cosillas a tener en consideración:</p>
<ul>
<li>Los Observadores en Rails utilizan el <a href="http://en.wikipedia.org/wiki/Singleton_pattern" onclick="javascript:pageTracker._trackPageview('/outbound/article/en.wikipedia.org');">patrón Singleton</a></li>
<li>Donde se instancian los observadores</li>
</ul>
<p>Empezaremos por el segundo punto.</p>
<p>En Rails, existen dos puntos prefijados donde se instancian los observadores correspondientes a cada modelo.El primero es en el fichero <strong>initializer.rb</strong> en el metodo de clase <strong>process</strong> donde se invoca el metodo load_observers</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> process
...
<span style="color:#9900CC;">load_observers</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Con load_observers como sigue,</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> load_observers
      <span style="color:#9966CC; font-weight:bold;">if</span> gems_dependencies_loaded <span style="color:#006600; font-weight:bold;">&amp;&amp;</span> configuration.<span style="color:#9900CC;">frameworks</span>.<span style="color:#9966CC; font-weight:bold;">include</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:active_record</span><span style="color:#006600; font-weight:bold;">&#41;</span>
        <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Base</span>.<span style="color:#9900CC;">instantiate_observers</span>
      <span style="color:#9966CC; font-weight:bold;">end</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>En ActiveRecord::Base.instantiate_observers crearemos para cada modelo sus observadores y será aquí donde comienzen nuestros quebraderos de cabeza.</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#9966CC; font-weight:bold;">def</span> instantiate_observers
        <span style="color:#0000FF; font-weight:bold;">return</span> <span style="color:#9966CC; font-weight:bold;">if</span> <span style="color:#0066ff; font-weight:bold;">@observers</span>.<span style="color:#9900CC;">blank</span>?
        <span style="color:#0066ff; font-weight:bold;">@observers</span>.<span style="color:#9900CC;">each</span> <span style="color:#9966CC; font-weight:bold;">do</span> |observer|
          <span style="color:#9966CC; font-weight:bold;">if</span> observer.<span style="color:#9900CC;">respond_to</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:to_sym</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#008000; font-style:italic;"># Symbol or String</span>
            temp = observer.<span style="color:#9900CC;">to_s</span>.<span style="color:#9900CC;">camelize</span>.<span style="color:#9900CC;">constantize</span>
            temp.<span style="color:#9900CC;">instance</span>
          <span style="color:#9966CC; font-weight:bold;">elsif</span> observer.<span style="color:#9900CC;">respond_to</span>?<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:instance</span><span style="color:#006600; font-weight:bold;">&#41;</span>
            observer.<span style="color:#9900CC;">instance</span>
          <span style="color:#9966CC; font-weight:bold;">else</span>
            <span style="color:#CC0066; font-weight:bold;">raise</span> <span style="color:#CC00FF; font-weight:bold;">ArgumentError</span>, <span style="color:#996600;">&quot;#{observer} must be a lowercase, underscored class name (or an instance of the class itself) responding to the instance method. Example: Person.observers = :big_brother # calls BigBrother.instance&quot;</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>POR TERMINAR, lo hare en otro post : )</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/11/16/rails-observar-un-modelo-desde-un-plugin-problemas/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Rails: Orden de carga de los plugins</title>
		<link>http://blog.tenako.com/2008/10/19/rails-orden-carga-plugins/</link>
		<comments>http://blog.tenako.com/2008/10/19/rails-orden-carga-plugins/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 16:57:43 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[orden]]></category>
		<category><![CDATA[plugins]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=35</guid>
		<description><![CDATA[
madtrick:~/programacion/ror/diary madtrick$ ruby script/server webrick
=&#62; Booting WEBrick...
/opt/local/lib/ruby/gems/1.8/gems/activerecord-2.1.0/lib/active_record/base.rb:1667:in `method_missing': undefined local variable or method `acts_as_authorizable' for #&#60;Class:0x336e194&#62; (NameError)
        from /Users/madtrick/programacion/ror/diary/app/models/user.rb:21
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:215:in `load_without_new_constant_marking'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:215:in `load_file'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:354:in [...]]]></description>
			<content:encoded><![CDATA[
<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>ror<span style="color: #000000; font-weight: bold;">/</span>diary madtrick$ ruby script<span style="color: #000000; font-weight: bold;">/</span>server webrick
=<span style="color: #000000; font-weight: bold;">&gt;</span> Booting WEBrick...
<span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>activerecord-2.1.0<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>active_record<span style="color: #000000; font-weight: bold;">/</span>base.rb:<span style="color: #000000;">1667</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>method_missing<span style="color: #ff0000;">': undefined local variable or method `acts_as_authorizable'</span> <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #666666; font-style: italic;">#&lt;Class:0x336e194&gt; (NameError)</span>
        from <span style="color: #000000; font-weight: bold;">/</span>Users<span style="color: #000000; font-weight: bold;">/</span>madtrick<span style="color: #000000; font-weight: bold;">/</span>programacion<span style="color: #000000; font-weight: bold;">/</span>ror<span style="color: #000000; font-weight: bold;">/</span>diary<span style="color: #000000; font-weight: bold;">/</span>app<span style="color: #000000; font-weight: bold;">/</span>models<span style="color: #000000; font-weight: bold;">/</span>user.rb:<span style="color: #000000;">21</span>
        from <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>activesupport-2.1.0<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>active_support<span style="color: #000000; font-weight: bold;">/</span>dependencies.rb:<span style="color: #000000;">215</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>load_without_new_constant_marking<span style="color: #ff0000;">'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:215:in `load_file'</span>
        from <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>activesupport-2.1.0<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>active_support<span style="color: #000000; font-weight: bold;">/</span>dependencies.rb:<span style="color: #000000;">354</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>new_constants_in<span style="color: #ff0000;">'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:214:in `load_file'</span>
        from <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>activesupport-2.1.0<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>active_support<span style="color: #000000; font-weight: bold;">/</span>dependencies.rb:<span style="color: #000000;">95</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>require_or_load<span style="color: #ff0000;">'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:60:in `depend_on'</span>
        from <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>activesupport-2.1.0<span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>active_support<span style="color: #000000; font-weight: bold;">/</span>dependencies.rb:<span style="color: #000000;">456</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>require_dependency<span style="color: #ff0000;">'
        from /Users/madtrick/programacion/ror/diary/vendor/plugins/authentication_system/lib/authentication_system.rb:1
        from /opt/local/lib/ruby/vendor_ruby/rubygems/custom_require.rb:27:in `gem_original_require'</span>
        from <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>vendor_ruby<span style="color: #000000; font-weight: bold;">/</span>rubygems<span style="color: #000000; font-weight: bold;">/</span>custom_require.rb:<span style="color: #000000;">27</span>:<span style="color: #000000; font-weight: bold;">in</span> <span style="color: #000000; font-weight: bold;">`</span>require<span style="color: #ff0000;">'
        from /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.0/lib/active_support/dependencies.rb:509:in `require'</span>
...</pre></div></div>

<p>Eso fue lo que me encontre hoy al ir a probar unas cosillas en Rails.</p>
<p>El problema deriva del orden en el que se cargan los plugins residentes en <em>$RAILS_ROOT/vendor/plugins</em>, que a parecer es lexicografica, con lo cual yo me encontraba en la situacion de que el plugin A hacia uso del modelo M pero a su vez este modelo hacia uso de un metodo <a href="http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.juixe.com');" target="_blank">&#8220;mixeado&#8221;</a> en ActiveRecord::Base por el plugin B.</p>
<p>Por lo tanto, como A se cargaba antes que B ya teniamos montado el belen.</p>
<p>Tras preguntarle al señor google que como arreglabamos este desaguisado, este primero me dijo que ya habia mas gente con este problema allá por el 2006 (<a href="http://dev.rubyonrails.org/ticket/5468" onclick="javascript:pageTracker._trackPageview('/outbound/article/dev.rubyonrails.org');" target="_blank">1</a>) y (<a href="http://dev.rubyonrails.org/ticket/6418" onclick="javascript:pageTracker._trackPageview('/outbound/article/dev.rubyonrails.org');" target="_blank">2</a>) y que finalmente la solucion por la que se opto fue la <a href="http://dev.rubyonrails.org/changeset/7531" onclick="javascript:pageTracker._trackPageview('/outbound/article/dev.rubyonrails.org');" target="_blank">siguiente</a> :</p>
<p>En environment.rb ponemos config.plugins = {:plugin1,:plugin2,:all} pudiendo controlar asi, el orden en el que se carga dichos plugins,cuales se cargan, etc.El simbolo :all, evidentemente se utiliza para cargar todos los demas plugins.</p>
<p><strong>Actualizacion:</strong></p>
<p>Soy algo cortito, si me hubiera molestado en leerme lo que ponia en environment.rb no habria tenido ningun problema.Extraido de environment.rb:</p>
<blockquote><p># Only load the plugins named here, in the order given. By default, all plugins<br />
  # in vendor/plugins are loaded in alphabetical order.<br />
  # :all can be used as a placeholder for all plugins not explicitly named</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/10/19/rails-orden-carga-plugins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails: Errores al instalar login_generator (1.2.2) en Rails 2.1.0</title>
		<link>http://blog.tenako.com/2008/10/09/rails-errores-al-instalar-login_generator-122/</link>
		<comments>http://blog.tenako.com/2008/10/09/rails-errores-al-instalar-login_generator-122/#comments</comments>
		<pubDate>Thu, 09 Oct 2008 17:07:41 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rails error login]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=16</guid>
		<description><![CDATA[Si queremos  utilizar el gem (o es &#8220;la&#8221; gem, no tengo muy claro el genero) en rails 2.1.0 nos vamos a encontrar con lo siguientes problemas tras haberlo instalado:
Primer problema,cuando vamos a generar nuestro sistema de login.La extension de las plantillas nos causa el primer problemilla:

madtrick$ ruby script/generate login account
     [...]]]></description>
			<content:encoded><![CDATA[<p>Si queremos  utilizar el gem (o es &#8220;la&#8221; gem, no tengo muy claro el genero) en rails 2.1.0 nos vamos a encontrar con lo siguientes problemas tras haberlo instalado:</p>
<p>Primer problema,cuando vamos a generar nuestro sistema de login.La extension de las plantillas nos causa el primer problemilla:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">madtrick$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate <span style="color: #c20cb9; font-weight: bold;">login</span> account
      create  lib<span style="color: #000000; font-weight: bold;">/</span>login_system.rb
      create  app<span style="color: #000000; font-weight: bold;">/</span>controllers<span style="color: #000000; font-weight: bold;">/</span>account_controller.rb
      create  <span style="color: #7a0874; font-weight: bold;">test</span><span style="color: #000000; font-weight: bold;">/</span>functional<span style="color: #000000; font-weight: bold;">/</span>account_controller_test.rb
      create  app<span style="color: #000000; font-weight: bold;">/</span>helpers<span style="color: #000000; font-weight: bold;">/</span>account_helper.rb
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>layouts<span style="color: #000000; font-weight: bold;">/</span>scaffold.rhtml
No such <span style="color: #c20cb9; font-weight: bold;">file</span> or directory - <span style="color: #000000; font-weight: bold;">/</span>opt<span style="color: #000000; font-weight: bold;">/</span><span style="color: #7a0874; font-weight: bold;">local</span><span style="color: #000000; font-weight: bold;">/</span>lib<span style="color: #000000; font-weight: bold;">/</span>ruby<span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span><span style="color: #000000;">1.8</span><span style="color: #000000; font-weight: bold;">/</span>gems<span style="color: #000000; font-weight: bold;">/</span>rails-2.1.0<span style="color: #000000; font-weight: bold;">/</span> 
lib<span style="color: #000000; font-weight: bold;">/</span>rails_generator<span style="color: #000000; font-weight: bold;">/</span>generators<span style="color: #000000; font-weight: bold;">/</span>components<span style="color: #000000; font-weight: bold;">/</span>scaffold<span style="color: #000000; font-weight: bold;">/</span>templates<span style="color: #000000; font-weight: bold;">/</span>layout.rhtml</pre></div></div>

<p>El error deriva de que el script que genera el login sigue considerando que las plantillas tienen extension .rhtml, cuando eso ya no es asi.Ahora las plantillas utilizan la extension .html.erb</p>
<p>Por lo tanto para solucionar este problema lo que debemos de hacer es modificar la extension del fichero solicitado en el generador , login_generator.rb en este caso.</p>
<blockquote><p>En mi caso el fichero login_generator.rb se encuentra en <strong>/opt/local/lib/ruby/gems/1.8/gems/login_generator-1.2.2</strong> en otros sistemas puede que sea <strong>/usr/local/lib/ruby/gems/1.8/gems/login_generator-1.2.2</strong> o <strong>/ruby/local/lib/ruby/gems/1.8/gems/login_generator-1.2.2</strong></p></blockquote>
<p>Pasaremos de:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>17
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">m.<span style="color:#9900CC;">template</span> <span style="color:#996600;">&quot;scaffold:layout.rhtml&quot;</span>, <span style="color:#996600;">&quot;app/views/layouts/scaffold.rhtml&quot;</span></pre></td></tr></table></div>

<p>A:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>17
</pre></td><td class="code"><pre class="ruby ruby" style="font-family:monospace;">m.<span style="color:#9900CC;">template</span> <span style="color:#996600;">&quot;scaffold:layout.html.erb&quot;</span>, <span style="color:#996600;">&quot;app/views/layouts/scaffold.rhtml&quot;</span></pre></td></tr></table></div>

<p>Si ahora volvemos a intentar generar el sistema de login no tendremos ningun problema:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">madtrick$ ruby script<span style="color: #000000; font-weight: bold;">/</span>generate <span style="color: #c20cb9; font-weight: bold;">login</span> account
   identical  lib<span style="color: #000000; font-weight: bold;">/</span>login_system.rb
   identical  app<span style="color: #000000; font-weight: bold;">/</span>controllers<span style="color: #000000; font-weight: bold;">/</span>account_controller.rb
   identical  <span style="color: #7a0874; font-weight: bold;">test</span><span style="color: #000000; font-weight: bold;">/</span>functional<span style="color: #000000; font-weight: bold;">/</span>account_controller_test.rb
   identical  app<span style="color: #000000; font-weight: bold;">/</span>helpers<span style="color: #000000; font-weight: bold;">/</span>account_helper.rb
overwrite app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>layouts<span style="color: #000000; font-weight: bold;">/</span>scaffold.rhtml? \ 
 <span style="color: #7a0874; font-weight: bold;">&#40;</span>enter <span style="color: #ff0000;">&quot;h&quot;</span> <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #7a0874; font-weight: bold;">help</span><span style="color: #7a0874; font-weight: bold;">&#41;</span> <span style="color: #7a0874; font-weight: bold;">&#91;</span>Ynaqdh<span style="color: #7a0874; font-weight: bold;">&#93;</span> Y
       force  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>layouts<span style="color: #000000; font-weight: bold;">/</span>scaffold.rhtml
      create  public<span style="color: #000000; font-weight: bold;">/</span>stylesheets<span style="color: #000000; font-weight: bold;">/</span>scaffold.css
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>account
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>account<span style="color: #000000; font-weight: bold;">/</span>welcome.rhtml
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>account<span style="color: #000000; font-weight: bold;">/</span>login.rhtml
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>account<span style="color: #000000; font-weight: bold;">/</span>logout.rhtml
      create  app<span style="color: #000000; font-weight: bold;">/</span>views<span style="color: #000000; font-weight: bold;">/</span>account<span style="color: #000000; font-weight: bold;">/</span>signup.rhtml
      create  README_LOGIN</pre></div></div>

<p>Segundo problema.Tras solventar lo anterior, estamos ansiosos por probar nuestro sistema de login asi que vamos a nuestro navegador y tecleamos: <a href="http://localhost:3000/account/login" onclick="javascript:pageTracker._trackPageview('/outbound/article/localhost:3000');">http://localhost:3000/account/login</a></p>
<blockquote><p>En la anterior direccion asumimos lo siguiente:</p>
<ul>
<li>Que el controlador que hemos creado para gestionar las funciones de login tiene por nombre AccountController </li>
<li>Que tenemos una ruta en routes.rb  que funciona para esta peticion</li>
</ul>
</blockquote>
<p>Si probamos esto una bonita pantalla de error nos dara la bienvenida:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;">ArgumentError <span style="color: #000000; font-weight: bold;">in</span> AccountController<span style="color: #666666; font-style: italic;">#login</span>
&nbsp;
wrong number of arguments <span style="color: #7a0874; font-weight: bold;">&#40;</span>0 <span style="color: #000000; font-weight: bold;">for</span> <span style="color: #000000;">1</span><span style="color: #7a0874; font-weight: bold;">&#41;</span></pre></div></div>

<p>Bien, para solucionar esto debemos de modificar todos los @request.method que nos encontremos en nuestro controlador por @request.<a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html#M000787" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.rubyonrails.org');">request_method</a> para evitar colisiones con la palabra reservada de ruby <a href="http://www.ruby-doc.org/core/classes/Object.html#M000338" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');">method</a></p>
<p>Tras solucionar esto volvemos a probar nuestro sistema de login, pero un vez mas nos la dan con queso:</p>
<p>Segundo problema,</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"> NoMethodError <span style="color: #000000; font-weight: bold;">in</span> AccountController<span style="color: #666666; font-style: italic;">#login</span>
&nbsp;
You have a nil object when you didn<span style="color: #ff0000;">'t expect it!
The error occurred while evaluating nil.request_method</span></pre></div></div>

<p>Bien, bien.Veamos que pasa aqui.Como podemos observar el mensaje de error nos dice que el error ocurrio al tratar de evaluar <strong>nil</strong>.request_method.Pero oiga, como que nil!! Si yo estoy viendo @request.request_method.</p>
<p>Lo que pasa aqui es que en esta version de <a href="http://www.rubyonrails.org/" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.rubyonrails.org');">Rails</a>, <strong>@request</strong> (al igual que <strong>@params</strong>, <strong>@session</strong>, <strong>@flash</strong>, <strong>@cookies</strong>, <strong>@headers</strong>, <strong>@response</strong>) ha quedado en desuso en favor de los &#8220;accessor methods&#8221; que tienen el mismo nombre que las variables pero sin la arroba.Es decir donde tenemos @request.request_method pasamos a tener request.request_method y asi sucesivamente.</p>
<p>Probamos los cambios y nos encontramos con el tercer problema:</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"> NoMethodError <span style="color: #000000; font-weight: bold;">in</span> Account<span style="color: #666666; font-style: italic;">#login</span>
&nbsp;
Showing account<span style="color: #000000; font-weight: bold;">/</span>login.rhtml where line <span style="color: #666666; font-style: italic;">#1 raised:</span>
&nbsp;
undefined method <span style="color: #000000; font-weight: bold;">`</span>start_form_tag<span style="color: #ff0000;">' for #&lt;ActionView::Base:0x35a61dc&gt;</span></pre></div></div>

<p>login.rhtml luce de la siguiente forma:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%%</span>= start_form_tag <span style="color:#ff3333; font-weight:bold;">:action</span><span style="color:#006600; font-weight:bold;">=&gt;</span> <span style="color:#996600;">&quot;login&quot;</span> <span style="color:#006600; font-weight:bold;">%&gt;</span>
...
<span style="color:#006600; font-weight:bold;">&lt;%%</span>= end_form_tag <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>start_form_tag, tambien esta en desuso, en su lugar debemos de utilizar <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#M001699" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.rubyonrails.org');">form_tag</a>.De esta forma login.rhtml nos queda de la siguiente forma:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;"><span style="color:#006600; font-weight:bold;">&lt;%</span> form_tag <span style="color:#996600;">'/account/login'</span> <span style="color:#9966CC; font-weight:bold;">do</span>  <span style="color:#006600; font-weight:bold;">%&gt;</span>
...
<span style="color:#006600; font-weight:bold;">&lt;%</span> <span style="color:#9966CC; font-weight:bold;">end</span> <span style="color:#006600; font-weight:bold;">%&gt;</span></pre></div></div>

<p>Ahora por lo menos podemos probar nuestro login.Lo probamos y tras hacer click en el boton de login,nos encontramos con el cuarto error,</p>

<div class="wp_syntax"><div class="code"><pre class="bash bash" style="font-family:monospace;"> NoMethodError <span style="color: #000000; font-weight: bold;">in</span> AccountController<span style="color: #666666; font-style: italic;">#login</span>
&nbsp;
undefined method <span style="color: #000000; font-weight: bold;">`</span>find_first<span style="color: #ff0000;">' for #&lt;Class:0x365c8b0&gt;</span></pre></div></div>

<p>find_first es otro de los metodos en desuso.Debemos de cambiarlo por <a href="http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001298" onclick="javascript:pageTracker._trackPageview('/outbound/article/api.rubyonrails.org');">find</a>, con el simbolo :first como primer parametro y la opcion :conditions con la condicion que teniamos en find_first.</p>
<p>Es decir, pasamos de:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">find_first<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;login = ? AND password = ?&quot;</span>, login, sha1<span style="color:#006600; font-weight:bold;">&#40;</span>pass<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>A:</p>

<div class="wp_syntax"><div class="code"><pre class="ruby ruby" style="font-family:monospace;">find<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#ff3333; font-weight:bold;">:first</span>,:conditions<span style="color:#006600; font-weight:bold;">=&gt;</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#996600;">&quot;login = ? AND password = ?&quot;</span>, login, sha1<span style="color:#006600; font-weight:bold;">&#40;</span>pass<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span></pre></div></div>

<p>Si volvemos a probar, adivinad que pasa&#8230;.si, otro error.Por el quinto vamos,otra vez por elementos en desuso.En este caso se trata de la variable @session residente en el fichero login_system.rb.Cambiamos esta y las demas variables existentes en dicho fichero a sus &#8220;accesor methods&#8221; , guardamos y volvemos a probar&#8230; e-voilà!!</p>
<p>Funciona!!</p>
<p>Espero que todo este rollo le sea de ayuda a alguien : )</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/10/09/rails-errores-al-instalar-login_generator-122/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Rails: Claves foraneas en las migraciones</title>
		<link>http://blog.tenako.com/2008/10/08/rails-claves-foraneas-en-las-migraciones/</link>
		<comments>http://blog.tenako.com/2008/10/08/rails-claves-foraneas-en-las-migraciones/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 22:37:47 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rails clave foranea]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=13</guid>
		<description><![CDATA[Hay varias formas para indicar la restriccion que implica una clave foranea en nuestras tablas cuando estamos utilizando las migraciones para definir dichas tablas.
La primera y mas &#8220;tosca&#8221; consiste en indicar a pelo dicha restriccion:

class CreateOrder &#60; ActiveRecord::Migration
   def self.up
      t.string :name
      t.integer [...]]]></description>
			<content:encoded><![CDATA[<p>Hay varias formas para indicar la restriccion que implica una clave foranea en nuestras tablas cuando estamos utilizando las migraciones para definir dichas tablas.</p>
<p>La primera y mas &#8220;tosca&#8221; consiste en indicar a pelo dicha restriccion:</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> CreateOrder <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
      t.<span style="color:#CC0066; font-weight:bold;">string</span> <span style="color:#ff3333; font-weight:bold;">:name</span>
      t.<span style="color:#CC0066; font-weight:bold;">integer</span> <span style="color:#ff3333; font-weight:bold;">:user_id</span>
&nbsp;
      execute <span style="color:#996600;">&quot;alter table table add constraint fk_table_user <span style="color:#000099;">\ </span>
         foreign key (user_id) references users (id)&quot;</span>
&nbsp;
   <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
   ...
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Pero tambien podemos aprovechar algun plugin para facilitarnos el trabajo.Es aqui donde entra en juego este plugin que descubri hoy.</p>
<ul>
<li><a href="http://www.redhillonrails.org/redhillonrails_core.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.redhillonrails.org');">Redhillonrails_core</a></li>
</ul>
<p>Con este plugin podemos rehacer lo anterior de la siguiente forma:</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> CreateOrder <span style="color:#006600; font-weight:bold;">&lt;</span> <span style="color:#6666ff; font-weight:bold;">ActiveRecord::Migration</span>
   <span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#0000FF; font-weight:bold;">self</span>.<span style="color:#9900CC;">up</span>
      t.<span style="color:#CC0066; font-weight:bold;">string</span> <span style="color:#ff3333; font-weight:bold;">:name</span>
      t.<span style="color:#CC0066; font-weight:bold;">integer</span> <span style="color:#ff3333; font-weight:bold;">:user_id</span>
&nbsp;
      t.<span style="color:#9900CC;">foreign_key</span> <span style="color:#ff3333; font-weight:bold;">:users</span>,:user_id,:id
&nbsp;
   <span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
   ...
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Bastante mejor, no?.Este plugin tiene disponible adaptadores para mysql y postgresql.</p>
<p>Aqui teneis los <a href="http://www.redhillonrails.org/index.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.redhillonrails.org');">otros plugins</a> que tienen disponibles. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/10/08/rails-claves-foraneas-en-las-migraciones/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 a [...]]]></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>
		<item>
		<title>Ruby: metodos de clase privados</title>
		<link>http://blog.tenako.com/2008/09/18/ruby-metodos-de-clase-privados/</link>
		<comments>http://blog.tenako.com/2008/09/18/ruby-metodos-de-clase-privados/#comments</comments>
		<pubDate>Thu, 18 Sep 2008 15:57:15 +0000</pubDate>
		<dc:creator>farruco</dc:creator>
				<category><![CDATA[programacion]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[constantes]]></category>
		<category><![CDATA[dinamicas]]></category>

		<guid isPermaLink="false">http://blog.tenako.com/?p=3</guid>
		<description><![CDATA[Ayer aparecio una duda delante de mi y me asalto, ¿Metodos de clase privados?
La primera idea que me paso por la cabeza y que probe fue:

class Test
&#160;
private
def Test.class_method
p &#34;inside private class method&#34;
end
&#160;
end

Si pruebo este codigo en irb,

madtrick:~/programacion/ruby madtrick$ irb
irb&#40;main&#41;:001:0&#62; require &#34;test28&#34;
&#62; true
irb&#40;main&#41;:002:0&#62; Test.class_method
&#34;inside private class method&#34;
&#62; nil

Podemos ver que no, que esto no funciona porque [...]]]></description>
			<content:encoded><![CDATA[<p>Ayer aparecio una duda delante de mi y me asalto, ¿Metodos de clase privados?</p>
<p>La primera idea que me paso por la cabeza y que probe fue:</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:#CC00FF; font-weight:bold;">Test</span>
&nbsp;
private
<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#CC00FF; font-weight:bold;">Test</span>.<span style="color:#9900CC;">class_method</span>
<span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;inside private class method&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Si pruebo este 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;test28&quot;</span>
<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
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.class_method
<span style="color: #ff0000;">&quot;inside private class method&quot;</span>
<span style="color: #000000; font-weight: bold;">&gt;</span> nil</pre></div></div>

<p>Podemos ver que no, que esto no funciona porque me deja llamar al metodo perfectamente y todos sabemos que eso no puede pasar ya que en ruby los metodos privados solo permiten ser invocados con un &#8220;self&#8221; explicito.Realmente lo que acabo de decir no es del todo cierto, ya que los utilizando el metodo <em><a title="send" href="http://www.ruby-doc.org/core/classes/Object.html#M000334" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-doc.org');" target="_blank">send</a></em> para enviar el mensaje da igual la visibilidad del metodo que lo reciva.</p>
<p>Lo que no entiendo es porque falla, supongo que sera porque la restriccion de visibilidad que implica <em>private</em> solo afectara a los metodos de instancia de la clase.Si alguien quiere aportar mas luz sobre esto&#8230;</p>
<p>Volviendo al tema, probemos con el metodo private_class_method.Este metodo cambia la visibilidad de cualquier metodo a privada.Veamos 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:#CC00FF; font-weight:bold;">Test</span>
&nbsp;
<span style="color:#9966CC; font-weight:bold;">def</span> <span style="color:#CC00FF; font-weight:bold;">Test</span>.<span style="color:#9900CC;">class_method</span>
<span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;inside private class method&quot;</span>
<span style="color:#9966CC; font-weight:bold;">end</span>
&nbsp;
private_class_method <span style="color:#ff3333; font-weight:bold;">:class_method</span>
<span style="color:#9966CC; font-weight:bold;">end</span></pre></div></div>

<p>Lo probamos,</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;test28&quot;</span>
<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
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.class_method
NoMethodError: private method <span style="color: #000000; font-weight: bold;">`</span>class_method<span style="color: #ff0000;">' called for Test:Class
from (irb):2</span></pre></div></div>

<p>Esto ya es otra cosa,es lo esperado.Este metodo esta muy bien ya que permite cambiar la visibilidad a que por ejemplo herede nuestra clase.</p>
<p>Pero aun nos queda una manera mas de definidir metodos de clase que sean privados.</p>
<p>Como en ruby todo es un objeto, las señoras clases tambien son objetos (de la clase Class).Por tanto tambien pueden tener metodos de instancia, que a efectos practicos se comportan como los metodos de clase definidos de forma normal y corriente en una clase.</p>
<p>¿Y como añado yo metodos de instancia a una clase?Pues hay varios metodos pero el mas sencillo (o por lo menos eso me parece  a mi -se aceptan sugerencias) es el siguiente:</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:#CC00FF; font-weight:bold;">Test</span>
    <span style="color:#9966CC; font-weight:bold;">class</span> <span style="color:#006600; font-weight:bold;">&lt;&lt;</span> <span style="color:#0000FF; font-weight:bold;">self</span>
      private
        <span style="color:#9966CC; font-weight:bold;">def</span> class_method
         <span style="color:#CC0066; font-weight:bold;">p</span> <span style="color:#996600;">&quot;inside private class method&quot;</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>Lo que acabamos de hacer es abrir la metaclase o clase-virtual de la clase para añadir un el metodo class_method con visibilidad privada.Para el que no sepa que son las clases virtuales o metaclases, le recomiendo leer los enlaces que menciono al final del post.</p>
<p>Si ejecutamos esto 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;test28&quot;</span>
<span style="color: #000000; font-weight: bold;">&gt;</span> <span style="color: #c20cb9; font-weight: bold;">true</span>
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.class_method
NoMethodError: private method <span style="color: #000000; font-weight: bold;">`</span>class_method<span style="color: #ff0000;">' called for Test:Class
from (irb):2</span></pre></div></div>

<p>Una vez mas, funciona correctamente.</p>
<p>Si quieres saber algo mas sobre las metaclasses o clases-virtuales te recomiendo que le heches un vistazo a:</p>
<p><a href="http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html" onclick="javascript:pageTracker._trackPageview('/outbound/article/whytheluckystiff.net');" target="_blank"><em>Seein metaclasses clearly</em></a></p>
<p><a href="http://www.ruby-forum.com/topic/102986" onclick="javascript:pageTracker._trackPageview('/outbound/article/www.ruby-forum.com');" target="_blank"><em>Why virtual classes? </em></a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.tenako.com/2008/09/18/ruby-metodos-de-clase-privados/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
