Jun 14

What’s the difference between your application’s javascript code and its java/ruby/python/whatever code?

Think about it for a second. Done? Well, the answer is: none!

In today’s web applications your javascript code is no different from the rest of your code base but yet we treat it with disregard - and we’re all to blame.

We often see developers investing time writing all sorts of automated tests around their code base but fail to do the same for their javascript - and yet they get surprised when their client can’t click on a button on their web app that depends on that ajax call that has been manually tested once when the page was first released.

Ask yourself this question if you’re not sure if you should be testing your javascript: If it breaks, can my users still benefit from my app? - I think the answer for most web apps is obvious.

As for tools, I can only speak of two, JsTestDriver and screw-unit, the latter being the one we’re using in my current project at ThoughtWorks.

What I liked about screw-unit is that it’s very easy to get it up and running. Being a Behavior-Driven Testing Framework it’s not surprising it has a syntax similar to Rspec -which I prefer over JsTestDriver’s similarity to JUnit’s.

Take this class as an example:

function Greeter() {
  this.greet = function() {
    return "Hi";
  }
 
  this.render_hi = function(container) {
    $(container).text('Hi there!');
  }  
}

This is how a test written with screw-unit could look like:

Screw.Unit(function() {
  describe("Greeter", function() {
    it("should say Hi", function() {
      greeter = new Greeter();
      expect(greeter.greet()).to(equal, "Hi");
    });
 
    it("should render the message 'Hi there' inside the container div", function() {
      dom_test = $('#dom_test');
      dom_test.html("<div id='container'></div>");
 
      greeter = new Greeter();
      greeter.render_hi('#container');
 
      expect($('#container').text()).to(equal, "Hi there!");
    });
  });
});

Not too bad for a javascript test suite huh?

So the next time you write a javascript line of code, how about writing a test for it? Consider using screw-unit as your tool but if you have been writing tests using a different framework and you’re happy with it, share your experience.
I’m always keen to learn better ways of doing what I do.

Cheers!

Tagged with:
Apr 24

It’s been now over a week since we moved to Sydney and everything is just great. We’re still house hunting but I got a feeling we’ll have a home soon. :)

In the meantime, this morning I got a feature request on github to allow AppConstants to interpret YAML files with embedded code like this:

development: &default
  max_upload_in_bytes:  <%= 1.megabyte %>

I haven’t needed it myself but thought it would be a nice addition so my latest commit does exactly that. Let me know if you find any issues.

Tagged with:
Apr 10

Now several months after I announced my odyssey to obtain my Australian work visa, the time has finally come!

I’ll be flying to Sydney next week, April 15th, and as you can probably guess, I’m excited as hell! :) This starts an important new page both in my life and my career, but that’s not what this post is about. It’s about sharing the experience of living for over two years in Europe.

First off, I traveled. A whole lot. Both for work and leisure. I’ve been to 23 cities in 11 countries, which you can check on my map. Getting to explore all these different cultures was definitely rewarding and fun, to say the least. But I have my favorites, including Prague, London, Dublin and Bruges…

While in Madrid, I worked for Mirai España, the company that provided me with great professional experiences. I had the opportunity to work with a few very smart people that, in a way or another, contributed to improve my skills as a software engineer.  Not to mention the several conferences I attended, including QCon in London, RailsConf in Berlin and serveral others.

Being a rock/metal fan I am in the ideal place to see just about every band I always wanted to. Concerts in Europe are high quality, frequent and affordable and as such, I’ve attended a whole bunch of them:

- Metallica
- Megadeth
- Soilwork
- Machine Head
- Offspring
- Cavalera Conspiracy
- Within Temptation
- The Haunted
- At the gates
- Judas Priest
- Testament
- Nine Inch Nails
- AC/DC
- Rammstein
- Grave
- Krisiun
- Nile

On a more personal note Madrid is also the place where I met Enif, my beloved girlfriend. We are both very excited about this new experience and, of course, we’re moving together to Sydney, with plans of getting married next year! :D

As you can see, Europe has been kind to me and I will certainly miss the experiences, cities, cultures and people I’ve met. But I’m only making room for more and more interesting things that will certainly happen on the land down under. Let’s conquer it all!

Hopefully my next post will be written by the beach, in my new home in Australia.

Cheers, mate! :)

Tagged with:
Apr 09

This will come as no surprise to my closest friends, but I am a long time game development admirer. Although I’ve never done anything professionally I did spend some time in the past studying this amazingly interesting field - it’s my dark hobby. As hardware evolves and gamers demand more and more reality from their consoles, the game development industry is one of the few that basically didn’t suffer with the latest economic crisis.

3D games are getting more and more sophisticated to the point that it’s very hard for a single person, or even a small team, to develop something worthwhile - think of all the people you need to develop a game such as God of War III: screenwriters, artists, musicians, sound engineers, 3D artists, animators, programmers, level designers, combat designers, actors, voiceovers…

So I just wanted to have the experience of writing a full game, end-to-end, and that’s where FallingDreams comes in. To be able to do that in a short amount of time, it had to be something simple and that’s why I chose Tetris. Although simple, it does share most of the steps common to modern games development. It was a very interesting project to work at and you can grab the result here. The source code is also available on my github account, here.

FallingDreams is written in Java (JDK 6) and as such it should work fine on Windows, Linux and Mac OS. I tried to be as loyal as possible to the original Tetris rules, but you might find one thing or two that don’t work as one’d exepct.

Enjoy! ;)


Disclaimer: This was my first ‘full game’ and is not intended to be production ready. The code has definitely got room for improvement and it served as my playground where I experimented different design techniques, both game and general software related. And it doesn’t have a single line of tests - crucify me :P

As I said, it’s not supposed to be considered bug free but I’m sure people interested in games development can benefit from the source files. Feel free to fork it as well! It would be cool to see what people would do with it :)

Tagged with:
Feb 28

Back in January I announced a small but useful plugin called AppConstants, that basically provides a central place where you can store environment specific constants. And since I started using Rails 3 in the past week, I thought I’d make it Rails 3 compatible.

The code is really simple and - as I expected - the upgrade process was quite straight forward.

I’m not gonna write a guide here on how to upgrade your plugins to Rails 3 - there is plenty about that around the web - but instead, just show the steps I went through to upgrade mine. Similar plugins might have a similar upgrade path.

- Generators

My plugin makes use of a simple generator that copies its default constants file and initializer to Rails.root/config and Rails.root/config/initializers, respectively. In Rails 2.x it was located under Rails.root/vendor/plugins/app_constants/generators/app_constants and it was defined like so:

class AppConstantsGenerator < Rails::Generator::Base
  def manifest
    record do |m|
      m.directory('config')
      m.file('constants.yml', 'config/constants.yml')
      m.directory('config/initializers')
      m.file('load_app_constants.rb', 'config/initializers/load_app_constants.rb')
    end
  end
end

In Rails 3, the generators had to be moved to Rails.root/vendor/plugins/app_constants/lib/generators. Notice the root directory app_constants under generators has been removed as well. And the code was changed to this:

class AppConstantsGenerator < Rails::Generators::Base
  def self.source_root
    @source_root ||= File.expand_path('../templates', __FILE__)
  end  
 
  def copy_config_files
    copy_file('constants.yml', 'config/constants.yml')
    copy_file('load_app_constants.rb', 'config/initializers/load_app_constants.rb')
  end
end

We had three simple changes here:

- The generator now extends from Rails::Generators::Base: This class uses the Thor infrastructure to handle generators. - more info here.

- I had to implement the source_root class method, which basically tells your generator where to find your template files.

- The manifest method is now called copy_config_files - or anything you want.

The way this works is that, once you invoke the generator, Thor will sequentially call all instance methods in your generator class - or the only instance method in the example above. If your generator does a lot, it will allow for a better organization of your tasks.

And that’s it! I did change a couple of other things but that had to be changed anyway and are not related to the migration.

For Rails 2.3.x users, you’ll find a 2.3.x branch on github that should work for you.

Cheers

Tagged with:
Feb 25

Learning new programming languages is fun. And if it’s your 2nd, 3rd…Nth programming language you will eventually look for features you already know and love.

Coming from Ruby - but after having done my fair amount of Java for many years, among other things - I end up looking for features like blocks, open classes and syntax sugar like automatic generation of attribute accessors. These are hard to let go of.

Having decided to learn Objective-C recently, I was delighted to find out that all of these are available - for better or for worse - and wanted to share this analogy with its Ruby counterparts.

- Attribute accessors

In ruby, this class definition

class Person
  attr_accessor :name
end

implements for you the getters and setters of the instance variable name.

In Objective-C, the combination of the @property and @synthesize directives provides you with roughly the same result:

// in the interface file
@interface Person : NSObject
{
	NSString *name;
}
 
@property(retain) NSString *name;
 
@end
 
//in the implementation file
@implementation Person
 
@synthesize name;
 
@end

Now the compiler is responsible for writing those getters/setters for you.

- Open classes & blocks

Blocks in ruby are the structures that allow you to - among other things - iterate over arrays like this:

my_array.each do |item|
  puts(item)
end

Objective-C doesn’t have an ‘each’ method in its root array class (NSArray) but since it does support blocks and open classes, you could just write it yourself:

//in the interface file
@interface NSArray (each)
-(void) each: (void (^)(id *))block;
@end
 
//in the implementation file
@implementation NSArray (each)
 
-(void) each: (void (^)(id *))block {
	for (id *object in self) {
		block(object);
	}
}
@end

Yes, I know the syntax isn’t appealing, but using it in your program is a bit better:

[myArray each: ^(id *item){ 
    NSLog(@"Current item: %@", item); 
}];

Given the syntactic differences, the code above is very similar to its ruby counterpart. Iterating over an array is just one of the many things blocks are useful for. Others might include dealing with files, network sockets etc…

Blocks are powerful structures and are not created everyday, but it’s nice to know that you can resort to them when the time comes. ;)

Tagged with:
Feb 03

What?

In Ruby you have basically two ways of defining private methods:

# this is the first way to do it
class Test
  def say_hello
    puts "I'm a private method"
  end
  private :say_hello
end
 
# and this is the second way
class Test
  #other methods this class might have
  private
  def say_hello
    puts "I'm a private method"
  end
end

I see a small problem with both approaches. In the first one, and the most obvious, is that you need to duplicate the method name as well as add an extra method call - private - just to change its visibility.

The second approach avoids this but adds the risk of accidentally putting a method that is intended to be public under the private section of the source file, which can render an annoying debugging session.

Why?

Personally, I like to have a smooth reading flow in my source files. That means that if the public method_a makes use of the private method_b, I want method_b defined right below its caller, which is possible - but verbose - using the private method call:

class Test
  def method_a
    method_b
  end
 
  def method_b
    puts "I'm a private method"
  end
  private :method_b
end

But can be somewhat harder to accomplish if you decide to split your source file in sections:

class Test
  def method_a
    method_b
  end
 
  #just another public method. We might have several
  def method_c
    method_b
  end
 
  private
 
  def method_b
    puts "I'm a private method"
  end
end

I wanted to be able to define a private method with a single reserved keyword…

How?

What if I could define a private method using this new syntax:

class Test
  def_p say_hello
    puts "I'm a private method"
  end
end

It turns out I can.

Notice the def_p keyword? This is a new keyword I created by changing ruby’s parser and that behaves mostly like the def keyword, except that it defines a private method instead.

If you wanna read the code that allows this behavior and try it yourself, download the patch I wrote and apply it to the ruby source code - I patched version 1.9.1-p376.

After applying the patch, just build ruby as usual:

$ ./configure
$ make

And then try running this script:

class Test
  def_p say_hello
    puts "I'm a private method"
  end
end
Test.new.say_hello

You should see the following output:

pvt.rb:10:in `': private method `say_hello' called for # (NoMethodError)

Happy hacking :)

Tagged with:
Jan 23

It’s funny how every Rails application I - and possibly you - work on ends up needing some sort of per-environment global constants.

Examples may include the application url - It might be used in account activation emails and thus should be different between the development and production environments.

Or perhaps your application depends on external services that, depending on the environment, are available in different URIs.

There are a couple solutions out there but my needs were simple and straightforward, thus I developed a small rails plugin that is the simplest thing that could possibly work: AppConstants.

It’s been useful for my current project and I hope it can be useful to someone else too ;)

Tagged with:
Jan 13

In one of my Rails projects I’m using Sphinx to provide full-text search capabilities. To integrate both worlds I chose Thinking Sphinx, which is just great and so far has met all of my expectations.

Also, as I previously mentioned, I’m using RVM to manage my ruby installations on both my development and production machines and this setup is what motivated this post.

I use Monit to monitor the services running on my production server - nginx, mysql, php - and as of the first deploy of this application, it only made sense to also monitor Sphinx.

In order to create an initialization script, I would need at least a way to start and stop sphinx from the command line, which, using Thinking Sphinx, can be done using these rake tasks:

$ rake thinking_sphinx:stop
$ rake thinking_sphinx:start

It’s worth mentioning now that I don’t run sphinx as root. I run it with the same user my rails application uses. For the purpose of this post, let’s call it deploy.

When I tried using my script I got errors such as these:

Missing the Rails 2.3.5 gem. Please `gem install -v=2.3.5 rails`, update your RAILS_GEM_VERSION setting in config/environment.rb for the Rails version you do have installed, or comment out RAILS_GEM_VERSION to use the latest version installed.

After some digging around I found that the GEM_HOME environment variable for my deploy user wasn’t being set correctly - something to do with rvm, but not quite sure - and to fix this, well, I just had to set it, leaving the final working version of my script somewhat like this - simplified :

#! /bin/sh
 
### BEGIN INIT INFO
### END INIT INFO
 
set_path="cd /your/rails/app/root; export GEM_HOME=/path/to/your/gems; RAILS_ENV=production;"
 
case "$1" in
  start)
        echo -n "Starting sphinx: "
                su - deploy -c "$set_path rake ts:start" >> /var/log/sphinx.log 2>&1
        echo "done."
        ;;
  stop)
        echo -n "Stopping sphinx: "
                su - deploy -c "$set_path rake ts:stop" >> /var/log/sphinx.log 2>&1
        echo "done."
        ;;
      *)
            N=/etc/init.d/sphinx
            echo "Usage: $N {start|stop}" >&2
            exit 1
            ;;
    esac
 
    exit 0

There are 2 things happening here. First, regardless of the user I’m running this init script as, I drop privileges in order to execute the rake task with my deploy user. Second, I set the GEM_HOME environment variable to stop getting the ‘gem not found’ errors.

After that, monit was able not only to monitor my sphinx instance, but also (re)start/stop it with the correct user.

I’m no Linux wizard so if you wanna suggest improvements to this script, feel free to do so!

Tagged with:
Jan 02

Today I read a nice post - in Portuguese - by Fábio Akita on how to manage multiple ruby versions on your machine. I’ve tried it once with some tool I can’t even remember the name but failed miserably.

But this time things look very different. The tool here is the rvm - short for Ruby Version manager - and it works just great.

Let’s cut to the chase and imagine that you, like me, want to run/develop/test your code on both ruby 1.8.7 and ruby 1.9.1. These steps would get you up and running in a few minutes:

Install rvm:

$ gem sources -a http://gemcutter.org/
$ gem install rvm
$ rvm-install
$ echo "if [[ ! -z $HOME/.rvm ]] ; then source $HOME/.rvm ; fi" >> ~/.bash_profile
$ source ~/.rvm/scripts/rvm

Install the ruby interpreters you want to use:

$ rvm  install ruby-1.8.7-p160
$ rvm  install ruby-1.9.1

Now it’s important to notice that at this point you have separate gem installations for each of the interpreters you’ve installed in the previous step. That said, just go ahead and switch between your interpreters and use your command line scripts - ruby, gem, etc… - as usual.

Switching between interpreters:

$ rvm ruby-1.8.7-p160  #switch to the specified version 
$ ruby -v
ruby 1.8.7 (2009-04-08 patchlevel 160) [i686-darwin9.8.0]
$ gem install rails  #note I'm not using sudo since the new gem paths point to the user's home directory 
 
$ rvm ruby-1.9.1  #switch to the specified version 
$ ruby -v
ruby 1.9.1p376 (2009-12-07 revision 26041) [i386-darwin9.8.0]
$ gem install rails  #note I'm not using sudo since the new gem paths point to the user's home directory

And that’s it, just go on and install rails, merb, sinatra or whatever rocks your boat!
rvm will work with MRI/YARV, JRuby, Ruby EE and Rubinius. Enjoy and don’t forget to check rvm’s website for the complete documentation! :)

Tagged with:
preload preload preload