format internet:

…please wait (48% completed)…

Posts Tagged ‘ruby’

Ruby on Rails on unofficial Chrome OS

Posted by javier ramirez on September 29, 2009

update: I thought this Chrome OS distribution was THE google distro. I was wrong. It’s just someone who used SUSE Studio to make a customized version of Open SUSE around the Chromium theme. With the site being on a google site and the code on a google code repository, I thought this was it, but no.. this distro is totally unrelated to google.

Chrome OS is by now just a bit more than a curiosity. In the meanwhile, you can go and download a non-official distribution mimicking what it could be, but be warned, all you are going to get is an Open Suse distribution with Chromium installed and a blue theme with a cute logo. Hopefully the real ChromeOS will be much lighter and more user-friendly.

Starting the virtual appliance from VirtualBox is easy. You create a new virtual media with the virtual media manager and then a virtual machine using this new media. That should be it. If you leave the default options (64MB) you’ll end up with a really slow boot. I set the base memory to 512K and things are much better.

What will you find in this distribution apart from Chromium? Zip, Zero, Null.. or if you are into ruby, nil.

Truth is, this distribution is a bit too rough around the edges (when it comes to internationalization, even if it ask you for the keyboard settings, it will just ignore them), but being a SUSE, you can install whatever you want. The only thing you’ll need is the root password. Since I’m such a hacker it took me almost no time to realize the root password was “root” (my other options being “sergei”, “larry” and “640Koughttobeenough”.

Once you have root access, you can use Yast for installing anything you might need. Just for fun I installed ruby, rubygems and sqlite3 via Yast, and then rails using gem. I had to run a gem update –system so I could use rails 2.3.4 and I generated a scaffold to see if everything was fine. Well, it was :)

ruby on rails running on google chrome os

ruby on rails running on google chrome os

Well, even if it was utterly useless, at least I found a cool way of making customized SUSE distros in an easy way ;)

Advertisement

Posted in 1771, development, javier ramirez, ruby, ruby on rails | Tagged: , , , , , , , | 4 Comments »

Multiple rubygems versions, GEM_HOME and GEM_PATH

Posted by javier ramirez on September 28, 2009

Installing rubygems is failrly easy and it’s great to have a package manager so you can forget about manually installing and upgrading the components you use. After installing a gem, you can require it from any ruby script and use it hassle-free. Well, given your ruby interpreter can find it.

When you install rubygems, a lot of default configuration is done behind the scenes. If you must see to believe, you can run

gem environment

do you believe me now?

Unless you are on windows, you have probably experienced already that gems can get installed in different locations. If using a superuser account, the global configuration will be used, but with a regular account gems install under your home directory.

If you are not careful about how you install your gems, or if you are using rake gems:install from regular accounts, you might end up installing the same version of a gem twice. That’s not only WET (not DRY, bear with me here) but it eats up your poor HD.

Things can get a lot worse than that. Suppose you are working with both JRuby and Ruby MRI. When you use rubygems from JRuby, it will try to use a different gem location by default. So, depending on how you are installing gems, you could have up to three different copies of exactly the same version.

And if you are on ubuntu and you upgrade from an old version of rubygems to the latest one —you will have to if you install Rails 2.3.4; if you are having problems you can read right here how to update it— you might be surprised that your gems are being installed *again*. The reason is under older versions the default location was “/var/lib/gems” and the latest one defaults to “/usr/lib/ruby/gems”.

Well, four different copies of ActiveRecord 2.3.4 are three and a half more copies than I wanted, mind you.

So.. how can we stop this gem install frenzy? Easy. Don’t use the defaults. Each of your installations is using default values, but they can be easily overridden with command line parameters or much more conveniently with environment variables.

Remember the title of this post? Can you see anything there that would make a good candidate for environment variables? That’s right, all the rubygems versions honor the GEM_HOME and GEM_PATH variables, so if they are set they will be used.

Depending on your OS, you can set these variables in different places. I’m on ubuntu and a bit lazy, so I chose the easiest, which is by adding this to my .bashrc file.

export GEM_HOME=/var/lib/gems/1.8
export GEM_PATH=/var/lib/gems/1.8

And now, no matter what I’m using: Ruby MRI, JRuby, or the latest rubygems, my already installed gems will be used, and the new ones will be put in the same place.

Saving the world is a hard job, but someone has to do it.

Posted in 1771, development, jruby, ruby, ruby, ruby on rails, ruby on rails | Tagged: , , , , , , | 7 Comments »

it’s not the framework, it’s you

Posted by javier ramirez on July 21, 2009

I’m getting tired already of the hype about Ruby on Rails and how it is better than any other framework past, present or future.

Sure Rails is a cute piece of software, and Ruby is a gorgeous language (supposing you are into programming languages, that is), but if you take a critical look at Rails, you could just say it’s another MVC framework.. Big deal.. And with some coupling issues between the layers too, which are fortunately being targeted on Rails 3.

Moreover, if you take a look at some of its components they could frankly be better. ActiveRecord, for example, is a wrapper ORM, which is implicitly tying you to the physical database layer, with one class per table, as opposed to a mapper ORM such as DataMapper or Hibernate. And the principle of least surprise is kind of a joke when it comes to some of the ActionView helpers and the parameters you have to pass along.

Still, as we like to say around here “Ruby on Rails mola infinito”, and it’s right now my favourite framework for non trivial web applications.

So.. what makes this framework so special? Is it only the absence of configuration and the sensible defaults? Would we sell ourselves for a couple of parlor tricks like those? Surely not.. specially with so many frameworks providing already sensible defaults. Come on, even in Java you can kind of forget about writing so much XML code if you make proper use of annotations and the like. No, it has to be something else.

Ruby on Rails has something that transcends the framework itself. It has you. The Mighty Developer. The Early Adopter. The Status Quo Challenger. The so-called Community —whatever that means.

Bottom line is, when I get together with people working with Rails, they are always in search of the holy grail of web development —or the nearest tavern, whatever comes first.. you have to love that kind of pragmatism. We like to break our assumptions, to learn new things and forget about the ones we already know.

We embrace Rails *today* but we are willing to embrace any other tool as long as we like it better. Do you remember the months before the Merb-Rails love affair? Half the Rails developers I know were already making eyes at Merb without the slightest hint of shame.

And by challenging the system, we are obliged to keep learning… and to find new ways to build the web. And instead of trying to make a carbon copy of what we did before, we like to start anew, because that’s where the fun is.

Sure you can argue this attitude is not the exclusive property of the Rails community. And I would second you on that based on theory.. but in practice, I have seen other some other communities lack this need of challenging. Maybe it’s because they have maturity models and certifications and black belts and whatnot…. And maybe having so many constraints is killing creativity; but fact is in some environments trying to take a step forward is seen as something odd, not desirable.

Rails will pass —or not— but as long as we keep alive the spirit of embracing change, we are entitled to be on the fun side of web development.

So, if you ask me, that’s the secret ingredient of Rails. Sure the language and the framework are cool, but the real power of Ruby on Rails is you.. and me.

update: please read the comments, since I was a bit ambiguous in the post and some points needed further explanation :)

Posted in internet, javier ramirez, madrid, ruby, ruby on rails | Tagged: , , , , , | 10 Comments »

install nokogiri and libxml on ubuntu

Posted by javier ramirez on May 28, 2009

a quick one..

the scenario:
you want to install nokogiri on ubuntu but you cannot get the gem to install because of unmet dependencies

the solution:

sudo apt-get install libxml2 libxml2-dev libxslt1-dev
sudo gem install nokogiri

the end

Posted in development, javier ramirez, ruby | Tagged: , | 14 Comments »

Cucumber, Selenium, Webrat, and Windows

Posted by javier ramirez on April 27, 2009

I spent last Saturday hacking around with some really smart people in Madrid. It’s not widely known than in Spain there’s a thriving Ruby on Rails community -my guess would be a language thing- but if you take a look at some of the Rails patches, Hackfest winners or the official Rails documentation project, you would be surprised to see how many -and how good- contributions are coming from this side of the world.

Once in a while we like to get together and take code challenges, so we can learn from each other and eat pizza to match the stereotype ;)

Thing is I’m a Windows guy. I know I should be sorry, I know it’s for housewives (or househusbands for that matter), but that’s life. (disclaimer: I’m planning to switch to Ubuntu in the near future)

As you know, developing software in windows while entirely possible is a bit more difficult than in other systems, specially when it comes to compiling, forking and the like.

Last Saturday I was, as usual, the only windows at hand (the rest being a lot of Macs in different flavors and a lonely Ubuntu) and, as a part of the code challenge, I had to run some tests with Cucumber, Selenium and Webrat. Apart from libxml, that has been working flawlessly in my computer for months, no other binaries were involved, so you would think everything was working just fine.. well, think twice.

First problem was the test server couldn’t be started automatically. I didn’t investigate much about it (my guess being that a fork or a system call is being issued and Windows cannot cope with it) since it was easier just to start it manually before running the tests. Also it was faster, because it didn’t need to be started every time.

After this obstacle, when I was trying to run the tests, I was getting a cryptic Errno::EADDRNOTAVAIL message. At first I thought it was because of Selenium not being able to bind to the given port, but a quick test from the command line discarded that possibility.

I don’t know anything about webrat (yet) but as the song goes, with a little help from my friends I was able to locate the source of the problem. When connecting to remote control Selenium, Webrat is trying to bind to the address “0.0.0.0” and that’s something Windows doesn’t like.

All I had to do was opening the file “selecium_rc_server.rb” at the gem source and replacing “0.0.0.0” by “127.0.0.1”.

I was told I can do this much more clearly at the Webrat config, but I tried it out and I still had the same problem. Taking a look at the Webrat code I would say the config param is not honoured system-wide, but truth is I was in a hurry and I didn’t researched it thoroughly. I had a challenge to solve after all ;)

Once I did this, all was hunky dory. Selenium started, the form fields were filled in, the tests were passing (or not) and the result was displayed on my not-ansi console. Bummer.

Believe me, cucumber is not half the fun without the colors in the output. Fortunately enough, google can tell you where to find lots of ansi-aware console replacements. Unfortunately enough console2, my favourite, is not one of those.

So, there, it took a bit of extra work but now you can also run this neat stack in your good-old windows box.

Posted in development, javier ramirez, madrid, madridrb, ruby, ruby on rails, ruby on rails | Tagged: , , , | 6 Comments »

Scotland on Rails 2009

Posted by javier ramirez on March 30, 2009

De vuelta de la conferencia Scotland on Rails me vuelvo con unas cuantas cosas aprendidas/confirmadas

a) Lo de menos son las charlas (aunque sigue siendo importante que, si las hay, sean interesantes). Lo que importa es el ambiente que se genera alrededor . Creo que el futuro de los eventos de desarrollo va por menos charlas, o por charlas filosóficas.

b) Tener un nombre en la comunidad no garantiza que seas competente haciendo presentaciones. Lo que sí garantiza es que te aplaudirán digas lo que digas (o leas lo que leas, aunque lleve años publicado y no tenga ningún interés).

c) El feedback positivo en una conferencia será directamente proporcional a la gente que venga de otros países. Se ve que la cortesía hace que evalúes bien aunque cometas el suicidio de no tener wifi en un sitio lleno de geeks, haya pocos enchufes, y des un catering de todo a 100.

d) La comunidad Rails hispana es muy potente, técnica y personalmente. El día que nos dé por hablar en inglés la vamos a liar parda. Da gusto escuchar a cualquiera de los de la representación “española” formada por Sam, Rai, Blat, Xavier, Alfredo, Gaizka, Susana, Fernando G., Sergio, Christos, Luismi, Guillermo, Felipe, David, Raúl, Juanjo, Jaime (y yo mismo :p )

En cuanto a las charlas, las que me inspiraron algo fueron (en orden cronológico):

– Getting Git, por Scott Chacon. Muy didáctico y con un buen balance entre crash course y consejos para usuarios más avanzados. Me gustó tanto que en cuanto su libro se publique es muy posible que lo compre. EPIC WIN

– Building blocks of modularity, por Jim Weirich. A pesar de alguna diferencia de criterio que tengo en las categorías de “connascence”, me pareció una charla muy interesante. Lo mejor es que no tenía nada que ver con Ruby o Rails. Era una charla de ingeniería/arquitectura de software. Así sí. EPIC WIN

– Security – what Rails will and won’t do for you, por Rory McCune. Sin entrar en nada especialmente novedoso, hizo una muy buena exposición de seguridad, comprensible, con ritmo, y con algunos datos que me parecieron interesantes. Es posible que acabe cambiando el login en alguna aplicación después de escucharla. WIN

– Advanced deployment, por Jonathan Weiss. Estuve a punto de perderme esta charla porque el nombre es muy engañoso, pero afortunadamente una amiga me hizo leer la descripción de la charla y acabé viéndola. No va de cómo hacer deploy, sino de qué forma puedes lidiar con una instalación compleja que requiere rendimiento, en concreto muy enfocado a la capa de datos. Explicaba las diferentes opciones para que tu base de datos escale, bien con replicación master-slave, master-master, particionado vertical de base de datos, sharding.. o mucho más sencillamente aplicando los famosos KISS y less is more. Me gustó ver que varias de las soluciones que aportaba las tenemos en producción en algunos proyectos. Siempre reconforta ver que lo que has hecho confiando en tu instinto es algo que tiene sentido. WIN

– The Ruby Object Model, por Dave Thomas. Nada nuevo que no esté escrito hace años (de hecho en los libros de este señor), pero de todos modos muy bien explicado y con unas referencias muy bien puestas a Simula y Smalltalk, incluída alguna frase lapidaria de Alan Kay. Lástima que no dedicase unos minutos más (dos) para introducir la teoría de objetos y el concepto de mensaje. Es lo único que le faltó para que me pareciera brillante. EPIC WIN

Y las charlas a las que asistí y que me hicieron sentir decepcionado:

– Keynote por Marcel Molina. Me alegro de que sepas leer y de que conozcas la página archive.org. El resto de la sala también tenemos internet en casa y también sabemos leer. Quizás sea especialmente duro porque en todas las charlas que he visto de Marcel me ha parecido brillante y esperaba mucho de esta keynote. FAIL

– Merb and Rails 3.0, por Yehuda Katz. Quitando el momento “teletienda engine yard de los primeros minutos”, me pareció en algunos puntos demasiado agresivo, en otros demasiado técnico, en otros demasiado ambiguo, y en otros pelín soberbio. Puede que por eso me dijeran que me parezco a él :P No me gustó su charla, pero he de reconocerle que de no haber sido por él puede que nunca se hubiera inventado el famoso juego “muerte violenta en seis movimientos”. De nuevo puede que sea un pelín duro porque Merb me gusta mucho y esperaba una charla espectacular. FAIL

– Server to server communication using XMPP and Ruby, por George Palmer. Dar una charla de XMPP sin hablar de XMPP y sin estar seguro de las siglas tiene su mérito. Dar una charla de 45 minutos en 20 tiene su mérito. Jactarse de no haberse leído un manual de 108 páginas porque es demasiado grande y luego no saber contestar a ninguna pregunta diciendo “pues esto estaría bien que lo hiciera, pero no sé si lo lleva”, tiene su mérito. Y a pesar de todo el FAIL no es absoluto porque la puesta en escena y la presentación multimedia me gustaron. Salvado por las slides de ser un EPIC FAIL.

A pesar de que el nivel de las charlas no me pareció óptimo y de que varios detalles de organización me parecieron muy malos (como que se llame “scotland on rails” y luego se quejen de que está demasiado orientada a Rails), el balance general que me llevo de la conferencia es bueno.

La experiencia fue muy interesante, la compañía inmejorable, y nada como ir a una de éstas para estar al día en tendencias de camisetas, zapatillas, y portátiles y gadgets cool ;)

Las fotos de la conferencia se están subiendo a flickr

p.s. gracias a aspgems por el detalle de hacerse cargo de mi viaje.

Posted in conferences, ruby, ruby, ruby on rails, ruby on rails | Tagged: , , | Leave a Comment »

Actualizando rubygems a la versión 1.3.1

Posted by javier ramirez on December 2, 2008

Hace un rato iba a instalar la última versión de merb, pero para instalar necesitaba tener al menos la versión 1.3.0 de rubygems, así que le he hecho el clásico

>gem update --system

con el siguiente resultado:

Updating RubyGems
Updating rubygems-update
Successfully installed rubygems-update-1.3.1
ERROR: While executing gem ... (NameError)
undefined local variable or method `remote_gemspecs' for #

Sin embargo un segundo intento me decía esto

>gem update --system
Updating RubyGems
Nothing to update

(principio de la mínima sorpresa, ahem… )

Bien.. en teoría tengo la gema gem-update 1.3.1, de hecho un “gem list” parece que me dice que la tengo instalada, pero si hago un “gem –version” me dice que sigo en la 1.2.0

Por si acaso intento un “gem check” y un “gem pristine” sin éxito.. Y ahora qué? Ahora toca buscar en google, claramente.. tres enlaces después, parece que la solución comúnmente utilizada es la siguiente

>gem install rubygems-update
>update_rubygems

un minuto y tropecientas líneas de log después, ya puedes hacer un

>gem --version
1.3.1

oeeeeeeeeeee

p.s. en serio.. era necesario complicarlo *tanto* ?

searchwords: gem update rubygems-update update_rubygems merb

Posted in development, javier ramirez, ruby | Tagged: , , , | 3 Comments »

Bienvenida Ms libxml

Posted by javier ramirez on July 17, 2008

Charlie Savage necesitaba hacer uso intensivo de xml para su proyecto mapbuzz y, como ninguna de las soluciones que había en Ruby era realmente buena (falta de funcionalidades, lentitud…) decidió retomar libxml-ruby para ponerlo al día y dejarlo funcionando.

El resultado no puede ser más prometedor según lo que anuncia en su blog

Al fin vamos a tener un parser XML con validaciones, XSLT, XML Schema, DTD, XPath y rendimiento razonable… y funciona en windows, que no está nada mal “for the rest of us”.

searchwords: xml, libxml, parser, DOM, SAX, ruby xml validating parser

Posted in development, javier ramirez, ruby | Tagged: , , , | Leave a Comment »

[Q&A] Diferencia entre nil y empty

Posted by javier ramirez on July 5, 2008

Inauguro una nueva serie en el blog. Como sabéis, me gusta participar en las listas de correo para aprender de los gurús, y para echar una mano cuando puedo a la gente que tiene dudas.

De vez en cuando respondo a mensajes en las listas de correo que me parecen dudas genéricas. Otras veces contesto a problemas con los que me he encontrado antes y que no eran fáciles de encontrar en la documentación. Creo que puede ser interesante referenciar estos mensajes en el blog para darles un poco más de visibilidad.

Podrás encontrar todos esos posts marcados con el tag y la categoría format_internet_q&a

En este primer caso de la serie, alguien planteaba cuál es la diferencia entre nil y empty. En concreto, quería entender porqué pasaba esto

x = ""
=> ""
x.nil?
=> false
x.empty?
=> true

Puedes encontrar debajo mi contestación a esta pregunta

> soy nuevo en ruby y me esta gustando mucho el lenguaje me gustaria que me dijeran que diferencia hay entre nil y empty

bueno.. aquí sería interesante si eres nuevo en ruby o si eres nuevo en cualquier lenguaje orientado a objetos. Te lo digo porque el equivalente a nil en muchos otros lenguajes (javascript, java, c++, c#…) es null.

voy a intentar hacer esto rápido.

ruby es un lenguaje muy orientado a objetos, hasta el punto de que todo es un objeto (a diferencia de otros lenguajes, que tienen tipos básicos a los que normalmente se llaman primitivas y luego objetos).

la forma normal de crear un objeto, es utilizar el método new de la clase correspondiente, por ejemplo

Array.new

Cuando llamas a new, se asigna espacio en memoria para alojar un objeto de esa clase, se le asigna internamente un id, y se guarda la referencia a ese objeto en una tabla que ruby lleva internamente. En la línea anterior, verás que hemos creado un Array, pero ni guardamos en ningún sitio una referencia a ese array, no podremos hacer nada con él. Aquí es donde entran en juego las variables. Si haces

a=Array.new

Estás creando un objeto, que se guarda internamente en la memoria, y además estás creando una variable llamada a, que apunta a la referencia de ese objeto en la memoria. De esta forma, cada vez que tu haces algo como

a.size

realmente lo que estás haciendo es invocar al método size del objeto al que apunta a. Ahora si haces

a=Array.new
b=a

Tienes dos variables, pero las dos apuntan al mismo objeto, de forma que si modificas tanto a como b, estás modificando el mismo objeto.

Con esto lo que quiero que veas es que por un lado van los objetos, que es donde realmente se guardan tus valores y se ejecutan tus métodos, y por otro lado las variables, que simplemente valen para apuntar a esos objetos. Si creas un objeto y ninguna variable está apuntándole, ruby lo eliminará de memoria tan pronto como pueda, ya que es inaccesible y nadie lo va a usar.

Teniendo medio claro lo que es un objeto y lo que es una variable, es posible tener una variable que no apunte a ningún sitio. Esto a veces se llama una variable no inicializada (aunque en realidad no es el único caso en el que pasa). Cuando una variable no apunta a ningún sitio, apunta a nil.

a=nil

Eso en muchos lenguajes es una variable que no apunta a ninguna parte. En Ruby es una variable que apunta al objeto nil (porque nil es también un objeto), pero la explicación te vale igual. nil se utiliza para indicar una variable que no apunta a ningún sitio, bien porque no se ha inicializado, bien porque se le ha asignado nil expresamente.

Si tú haces lo que decías en tu mail

x=""

x es una variable que está apuntando a un objeto que es la cadena “”. Al apuntar a ese objeto, puedes utilizar todos los métodos que da la clase String. Por ejemplo,puedes hacer

x.upcase

eso te va a devolver “”, porque la cadena “” en mayúsculas es “”, pero como ves, tienes un objeto String, que puedes usar como quieras. Por lo tanto, si haces

x.nil?

te va a decir “false”, ya que x no apunta a nil, sino a un objeto String vacío. Al estar vacío, si le pides

x.empty?

te va a decir que,efectivamente, la cadena está vacía. Sin embargo, no es nil, porque apunta a un objeto de tipo String que está referenciado en memoria.

Espero que te haya quedado medio claro.. si venías de un lenguaje orientado a objetos, seguro que ya sabes cómo va esto. Si no venías de un lenguaje orientado a objetos, quizás te valga la pena leerte algo de teoría de orientación a objetos para entender cómo funciona ruby. Te será especialmente útil para entender cosas como las variables de instancia, de clase, herencia, constructores, etc. Puedes programar sin conocer todo eso, pero vas a desaprovechar muchas de las funcionalidades disponibles.

puedes encontrar el hilo de este post en

https://listas.escomposlinux.org/pipermail/rubies/2008-July/000721.html

searchwords: nil, empty, ruby programming language, garbage collector, object oriented programming

Posted in development, format_internet_q&a, javier ramirez, ruby | Tagged: , , , , , | 1 Comment »

masochism: plugin para replicación master-slave en MySQL

Posted by javier ramirez on May 18, 2008

Recientemente me he encontrado con la necesidad de trabajar desde Rails contra una base de datos MySQL replicando en modo master-slave.

Replicación Master-Slave In a Nutshell:

La idea de montar un master-slave es tener la base de datos maestra para realizar las modificaciones a la base de datos, y usar la/las bases de datos esclavas para realizar las lecturas. De esta forma, las operaciones de lectura, que son las más habituales, se pueden balancear entre diferentes instancias de una base de datos.

Por otro lado, cada vez que se hace una modificación en la maestra, esta modificación se replica en las esclavas, de forma que los datos siempre están sincronizados.

Esta imagen del manual online de MySQL es muy explicativa

mysql master slave

Claramente este esquema nos puede ayudar mucho de cara a la escalabilidad de una aplicación, ya que la base de datos es uno de los cuellos de botella típicos.

Lo que necesitamos en este caso, es asegurarnos de que todas las operaciones de escritura van contra la conexión de la maestra, mientras que las lecturas van por una conexión esclava.

Una de las ventajas de usar un framework- en este caso Rails, pero podría haber sido cualquier otro- es que tu aplicación tiene una arquitectura bien definida. O al menos debería. Esto significa que al usar Rails tenemos bajo control las operaciones que se hacen contra la base de datos, con lo que identificar las de lectura y las de escritura debería ser simple. Si seguimos las reglas del framework, las operaciones contra la base de datos pasarán siempre por el modelo y por los métodos que AR nos proporciona.

Al final, el número de métodos que realmente acaban accediendo a la base de datos son más bien pocos, con lo que podríamos jugar un poco con el framework, establecer dos conexiones con la base de datos (una con la maestra, y otra con la esclava) y decidir qué conexión va a usar cada método. Así todos los métodos “find” y similares irían por la esclava, y los “delete”, “insert”, etc.. irían por la maestra.

Esto mismo es lo que el plugin masochism hace automáticamente por nosotros. El plugin viene de la mano del hiperproductivo Rick Olson.

Uno de estos días tendré que contar en más detalle cómo va, pero el resumen ejecutivo es que lo instalas, le añades una conexión master_connection en tu fichero database.yml, llamas a un método en uno de tus initializers… y te olvidas. A partir de ahí todo funciona de forma transparente (siempre que hayas configurado tu master/slave de MySQL previamente, claro).

De momento le he encontrado una única pega. Entre los métodos que se envían a la base de datos maestra no está el método “execute”, que es el típico método que sólo utilizas cuando quieres modificar algo en la base de datos. Sin ir más lejos, el (imprescindible) plugin Foreign Key Migrations usa ese método para crear las FK, por lo que si no nos aseguramos de que se usa la base de datos maestra, podemos tener problemas.

Le he mandado un parche (en realidad es añadir una palabra y una coma) a Rick , a ver si le parece apropiado incuírlo como parte del plugin.

update: y el patch ya ha sido incluído :)

Y a escalar!!

searchwords: scalability, mysql replication, master-slave, javier ramírez

Posted in development, javier ramirez, ruby, ruby on rails, ruby on rails | Tagged: , , , , , , , | 4 Comments »