<?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; plugin</title>
	<atom:link href="http://blog.tenako.com/tag/plugin/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.tenako.com</link>
	<description></description>
	<lastBuildDate>Sun, 10 Jul 2011 10:15:17 +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>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" 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" 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" 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>local<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" 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" 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" 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" 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>local<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" 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" 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> <span style="color:#006600; font-weight:bold;">|</span>const<span style="color:#006600; font-weight:bold;">|</span> 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> <span style="color:#006600; font-weight:bold;">|</span>const<span style="color:#006600; font-weight:bold;">|</span> 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" 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" 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>local<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" 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>local<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" 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" 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" 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> <span style="color:#006600; font-weight:bold;">|</span>observer<span style="color:#006600; font-weight:bold;">|</span>
          <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>
	</channel>
</rss>

