Using Authlogic for general email validation 1

Posted by caike on November 05, 2009

In case you are using Authlogic for authentication in your Rails apps, then you are probably using its email format validation in the user registration step. You get this validation for free just by specifying your model to acts_as_authentic:

class User < ActiveRecord::Base

  acts_as_authentic

end

That’s it for the user model and its registration field validations (login, email and password).

But what if you have some other model in your application with an email field that you also want to validate ? You could just get your favorite email format regexp and use it with the validates_format_of method:

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => /SomeRegexpYouGotFromGoogle/

end

But that would be decentralizing the email validation concern - totally anti-DRY and error-prone.

A better solution would be to use the email regexp that’s in Authlogic, which is the same that’s already validating your user model email field.

class Band < ActiveRecord::Base

  validates_presence_of :manager, :description
  validates_format_of :email, :with => Authlogic::Regex.email

end

That’s it. Hope it helps someone keep their code clean.

Writing expressive code 7

Posted by caike on October 07, 2009

Software developers read a lot more code than they actually write. An application source code is nothing but a story written using a specific language. It has state and describes behaviour.

Code written once, will be read millions of times. For the most part, it will be read by a compiler who doesn’t really look for anything but correct syntax. Compilers are not into reading stories. They are too busy for that. Just like assembly-line workers, they follow a plan and do exactly what they were told. As soon as they pass things over to the runtime, they are done. On the other hand, we developers are not like that, are we ? No, we are not!

We are software craftsmen. We like to read stories and even get paid to write some every once in a while.

man_reading_book

http://www.flickr.com/photos/dhammza/91435718/

Think about it the next time you hack that magic one-liner in an application. Do you think you will be able to read that code-golf champion piece of code the next time you look at it ? What if it is not you, but someone else reading it ?

“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live (…) Alternatively, always code and comment in such a way that if someone a few notches junior picks up the code, they will take pleasure in reading and learning from it.” - Ward Cunningham, CodeForTheMaintainer

An example I like to use for expressive code is method parameters in Ruby. Let’s say you want to stay fit and write a method to calculate a body fat percentage. You write the following:

def body_fat_percentage(name, age, height, weight, metric_system)
end

Apparently it looks nice. Let’s see how it could be invoked:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", 30, 1.82, 90, 1)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", 32, 5, 300, 2)

In order to write those two calls you would probably have to check the right order for the parameters in the method’s signature. Even worse, every time you read that line you would have to check back its signature just to make sure that the last argument determines the metric system or that the third argument is actually the height and not the weight.

That sounds like a pretty boring story to read!

Let’s make this piece of code more expressive:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", :age => 30, :height => 1.82,
  :weight => 90, :metric_system => MetricSystem::METERS_KG)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", :age => 32, :height => 5,
:weight => 300, :metric_system => MetricSystem::FEET_LB)

All we need to do to the method signature is to replace the standalone arguments for a hash.

def body_fat_percentage(name, params={})
end

From the method body, the values can be accessed using the keys, like params[:age], params[:height], etc.

In a real life situation, this expressiveness would be achieved from writing our expectations as unit tests. We would first write our failing tests as how we wanted our code to look and act like. From that, we would head towards making the tests pass. When all is green, the tests would turn out to be the reference for how to call the method (running and never-obsolete documentation) so there’s no need to go back to the implementation of the method itself to learn how to to use it.

Writing expressive code often means writing more code, but it also means writing better code. It’s not about making things work, it’s about making things right.

Remote Pair Programming with Screen 5

Posted by caike on May 15, 2009

If you have ever felt the need to do remote pair-programming and didn’t know of any tools around to help you do that, here is a quick tip using Screen.

Screen is a window-manager that makes it possible to share a single session among users logged onto the same machine, allowing them to interact with each other in real time.

This assumes that you:

a) have access to at least one Linux/Unix box with Screen and SSH enabled.
b) are comfortable working with a command line editor (vi, vim, emacs, etc).

For this example we will be using Screen 4, which is probably already bundled with your favorite Linux distro or OS X. If you happen not to have it, apt-get/yum/port/whatever to install it.

In order to have multiusers on one Screen session, some file permissions need to be changed. Screen needs to be able to be run as root and the /var/run/screen folder needs some executing permission.

sudo chmod +s /usr/bin/screen
sudo chmod 775 /var/run/screen

Now the first user - let’s call it foo - can log in to the Linux box via SSH and start a Screen session named pairprog.

[foo@linuxbox ~]$ screen -S pairprog

The user foo, now on Screen, needs to turn on multiuser mode and grant access to his friend, the user named bar.

^A :multiuser on
^A :acladd bar

(^A means ‘control + A’, which is the way commands are passed to Screen)

Now it is time for the user bar to log in to the same Linux box and join foo’s Screen session.

[bar@linuxbox ~]$ screen -x foo/pairprog

Now both users should see each others’ activities.

Fire up your favorite command line editor, start a voice chat (using Skype or something) and you’re good to go in no time!

Update! It is worth mentioning that the user foo actually shared everything. This might cause security implications, since the guest user (bar) will act as the host user. You can give the host user read-only permission by:

^A :aclchg bar -w "#"

Probably the best way to use Screen for session sharing would be to create a new “public” user and use it as the host for the session. Place all the files under this public users’ directories or other public directories.

Thanks for pointing it out, Pigor!

DHH’s secret to high productivity

Posted by caike on May 09, 2009

I have had a great impression watching DHH’s keynote from this years’ RailsConf. According to him, although many changes have been made to the Rails codebase since he started the project 6 years ago, on the overall not that much has changed.

From the few times I’ve watched him speak, he always made it clear that out-of-the-box Rails is all he really uses or knows about. No surprise, since he has written the thing for himself exactly the way he needed it to be. Then a core team came along and extended it. Nice. Now we have people digging in for performance enhancement which will be seen in Rails 3. Great!

Its convention over configuration was never meant to be fit for everyone and every occasion. It will probably never be in the long run and I really hope it stays that way. If someone thinks they need to tweak a few things in Rails in order to accomplish something, then they should go ahead and do it and it’s awsome how most times it is as simple as writing a plugin or gem.

All the framework hype that we see happening today is way more than we will ever come to actually need.  His secret to high productivity is not really technology related. It’s all about renegotiating requirements.

If you are developing professional solutions for the enterprise (and by that I don’t mean enterprisey) and you’re still doing it the hacker way, then no platform will look good enough for you. If there is no communication involved in your development process, then you will either fail or spend a lot more effort on trying to develop something.

Five years have passed since Rails was released. All it offers, plus all the other gazillion testing frameworks and gems, will be completely useless unless you take your time to understand what really needs to be done.

You client doesn’t always know what he wants, but he sure knows what he does not want.

He may come up to you and ask you for something that will take you two weeks to develop. As a professional software developer, it is up to you to start from what he wants and get to what he needs. Maybe you can solve his problem with a completely different solution, and one that will take you one day to develop.

As DHH said it, in case you want chocolate, maybe a Twix that is in your pocket is all you need, rather than driving all the way downtown and getting a 15 dollar belgian chocolate.