soledad penadés
repeat 4[fd 100 rt 90]

Archive for the ‘php’ Category

20060501 My first application in Ruby On Rails

It's time to get serious with RoR! I finally decided that I would do some useful application to really learn how it works, and as I'm quite bored of doing applications for managing text (whether they are intranets, cms's, etc), I opted for recreating my old gallery script (which I did in php) in RoR. So I'm playing with images instead of just text.

This will give me the opportunity to test lots of extra functionalities of the framework, such as the famous integrated javascript effects, ajax, etc, as I want to improve my old gallery script, not simply redo it as it was in php.
So first thing I did was to make sure that I had a working updated version of ruby and rails. The best tutorial I have found which worked perfectly for me is this one: Building Ruby, Rails, LightTPD, and MySQL on Tiger, by Hivelogic. (Although I simply used it to update Ruby and Rails, but didn't build Lighttpd or Mysql).

With that I could be able to follow the recent tutorials and techniques, specially because I wanted to learn how to use a Login Generator, and there was something in the version of Ruby that I had which prevented me to install it (some lib error was thrown each time).

So my app has two parts, a public and an admin one (which was quite easy to anticipate). Once I managed to create the basic structure of controllers and models for the admin, I added the login functionality, as I don't want everybody to get into my app and modify pictures in there.

I used the Acts As Authenticated plugin, although I couldn't manage to get all the functionality that I expected so I took a look at the code of the Sudoku On Rails v5 tutorial at SobreRailes (sorry, spanish only!) and completed it with the missing functionality (basically, it was the activation stuff which was not generated, don't know why). It was sweet and smooth. If I had had to write it manually I would have spent at least three days.

Then I wanted to have support for uploading images. At all, this is about pictures! So after some researching I found a little plugin called FileColumn which allows to get picture uploads working quite quickly, including resizing and automatic deletion if the associated record gets deleted (no more orphan files in the filesystem because of a poor integration between the models and their associated data! hooray!). But for the resizing stuff and thumbnails generation, I needed to have RMagick installed in my system, which I didn't have. So I found a nice tutorial in the RMagick site, which explained how to compile and install RMagick and GraphicsMagick on mac os x, as well as all the libraries on which they depend, as RMagick is like a bridge between ruby and GraphicsMagick. This step took me a bit of time, specially the step of compiling ghostscript, but as I followed the instructions exactly as specified, I had everything working at the end and I could generate thumbnails and a resized version when uploading images. (Also I was also reading one of the supercool books about the tube that mr.doob gave me for my birthday so time flew fastly! :D )
If I had had to do this in php even using the best helpers that I could, I would have spent at least one week.

Then I prepared a draft version of the public interface. Now I can navigate between pictures and albums, using thumbnails and the big images as well, it shows the descriptions for the album or picture, where available. The code is so simple and beatiful that I could get it tattooed. Or maybe do a t-shirt with it, see an example for getting the data of one album:

def album
@album = Album.find(params[:id])
unless @album.nil?
@pictures = @album.pictures
end
end

No more embedded SQL in the middle of the code, no need for manually loading classes which abstract the DB information for the rest of the php code and try to provide a way of artificial modelization of the data, no need to spend time reinventing the wheel!! :D

As I specified in the models that one album has pictures (has_many : pictures), and that each picture belongs to one album (belongs_to :album), RoR is intelligent enough to deduct things from the database and save me that precious time (as it sees an album_id column in a picture row… it obviously is pointing to an album row!).

Unfortunately by the moment the front end is extremely basic, it's pure html with little css applied to it. In the next iteration I will do tasks such as find out how to redefine part of the behaviour of the FileColumn to make it update the associated images too if I upload another image when editing a picture, beautify the front end, and maybe start with those nice ajax capabilities which are supposedly quite easy to use with RoR. It will also be nice to learn how to do the fantastic unit tests with the support that this framework provides, so all in all this promises to be very exciting.

Conclussion: I absolutely love Ruby on Rails.

Stay tuned for a next release - as I already got a port for installing it on my host, it can be whenever I get a decent working version!.

UPDATE: As some people want to take a look (miguev ;) ) I have uploaded the relevant code of the current version. It just has the important things i.e. the models definition, etc. If you want to have a working application you will need to create it first with the usual rails name_of_your_app, configure the database, etc, and then use this code where appropiate. It won't work by itself :P This is just for showing how things are linked between them: cl1ck version 0.1

20060128 Some things I want to give a try: results

Some months ago, I said I wanted to test several things, and here are the results:

  • CakePHP: it's promising although it lacks lots of documentation and I don't have time to guess how does it work. I'll wait until it is a bit more consolidated to have another look. I have been testing it today with a local copy of the xplsv.tv database (to have some real data where the tables are more related than in my blog), and although I managed to create the models, controllers, views and so on, I get stuck when it comes to simple things like specifying the relationships between tables, the maximum number of records retrieved each time… I know I could go and find the answers by digging into the code but hey, I want to save time, not spend it guessing how things work…
  • Flock: it didn't appeal to me, I don't use blogger as my blog platform and in general it didn't look much better than camino or firefox. It even was a bit slow. More of a hype than nothing really impressing. I'll have to wait a bit more, as its team said they are working on new improvements.
  • Pong: I ignored it completely. In fact I am using ping-o-matic.
  • flash 8: not yet…
  • ruby on rails: no time either :-(

And that's all!

20051207 Loving RoundCube

What's better than a Cube? A rounded cube!

After my I-hate-all-webmails post (sorry, in Spanish), I must recognize I have found one which is pretty decent (also very mac-ish): Round Cube.

It's still in alpha but works greatly and nicely, super ajax powered… and it's so clean…!

If you want to try it, use these installation instructions. Pretty straightforward.

A MUST have - I think it'll become the web2.0 webmail program ;-)

20051130 Naming PHP constants conventions

Doing a project with more people in php can be really complicated when it comes to naming constants. For some reason each people has his own way of naming things. Some people will like to start constants with an underscore, like _MYCONSTANT and some others will not, like MYCONSTANT.

The problems get stronger when things begin to appear repeatedly (specially if there's more than one programmer adding constants at the same time).

So what I did is try to find a way of naming which was meaningful and more or less consistent. I'll explain you so we can all benefit from the other's experiences…

There are several types of constants, depending on the purpose:

  • labels: something which appears with form controls, like "Enter the text here". These constants are prepended with LBL_
  • texts: text which appears on any place, but is not a label. These have a TXT_ prepended.
  • titles: which are used on page headers and section names: we prepend a TITLE_

This way if you split your code in modules, you can have constants like:

MODULE1_TITLE_INSTRUCTIONS
MODULE1_TXT_INSTRUCTIONS

and you won't have collisions like MODULE1_INSTRUCTIONS being used both for the title and for the text of the instructions by different programmers.

Also, constants are alphabetically ordered in the files. Not appended at the end with any order…

It could also be applied to more languages. In fact I somehow took some ideas from the way constants worked on MFC or visual basic (taking into account that I don't remember too much from those days so maybe it is not exactly as I thought…).

What do you think of this method? Do you have some suggestion that could make it better?

20051120 Hoy soy un poco más web 2.0

Le he puesto una nube de etiquetas (cloud tag) al blog, como cualquier web 2.0 que se precie. Es algo que quería hacer desde hace mucho y nunca encontraba ningún huequecito para hacerlo.

Me ha servido también para darme cuenta de que me quejo más que otra cosa (demasiados posts en la categoría quejas), así que a ver si me quejo menos y así crece el tamaño de las otras categorías. Porque además he hecho que, como en toda buena nube de etiquetas, las categorías con más elementos tengan un tamaño de letra mayor.

Para esto he hecho un pequeño truquito que os paso a relatar. La fórmula que he usado es dividir el número de posts de esa categoría por un número (en este caso 10), y redondear. De esta forma obtienes incrementos de 1,2,3 … según si hay 10, 20, 30,… o más posts de esa categoría. Con estos escalones, multiplico por un valor dado (en este caso 5) y con ello calculo un porcentaje final. Por ejemplo, una categoría que aparezca en menos de 10 posts tendrá porcentaje 100, que es el base. Una que tenga 10 pero menos de 20 posts, tendrá 105 como porcentaje.

Luego en la plantilla, se añade un style="font-size: $porcentaje_calculado%;" sólo si el porcentaje es mayor que 100, ya que hay muchos casos en los que se dará este supuesto, y así ahorramos ancho de banda.

Según vea que pongo más etiquetas, quizá cambiaré el valor por el que se divide el subtotal de cada una, para que haya más escalonamiento y se note más la diferencia… y así sigan habiendo bastantes posts en el supuesto anterior (porcentaje=100%)
Pero por ahora quedaba bien (ajustando a ojímetro).

Por supuesto, clicando en cada tag podéis ir a ver los posts etiquetados con esta tag. Y desde la página de ver los posts con esa tag, también podéis ir a technorati para buscar posts etiquetados con eso, no necesariamente míos.

Aún hay muchos posts que no están bien etiquetados, básicamente porque al principio de los principios en lugar de etiquetas tenía una especie de categorías que elegía y aplicaba a cada post, así que la mayoría de los antiguos no tiene etiqueta, a menos que los haya revisado y etiquetado consecuentemente.

¡A disfrutarlo!