Archive

Archive for the ‘Sviluppo Software’ Category

ruby performances

When you’re digging into your code in order to increase the performances you probably have to know a couple of things about how the ruby interpreter works. I’ve completed a couple of tests with several interpreters to show you how a simple change can impact.
The ruby interpreters i’ve used in these tests are:

  • ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0]
  • ruby 1.8.7 (2010-12-23 patchlevel 330) [i686-darwin10.7.0]
  • MacRuby 0.8 (ruby 1.9.2) [universal-darwin10.0, x86_64]
  • jruby 1.5.6 (ruby 1.8.7 patchlevel 249) (2010-12-03 9cf97c3) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_24) [x86_64-java]

Every time you call a method the ruby interpreter uses a hash structure for the lookup, this is an expansive task, so you can avoid this lookup every time you need to access an instance variable doing it directly with @variable instead of the attr_accessor methods.

This is the test script:

This is the result of the test in seconds (you can see the raw data here)
Ruby method vs variable access time

Another interesting optimization you can probably do is to use the interpolation whatever is possible. Look at this example:

this is the result of the test (and raw data):
ruby interpolation vs concatenation

auction system using bayeux and node.js

Imagine you want to serve a page with a list of auctions and you want to keep your users aware of what’s happening. For example when someone clicks the buyout button you want to let them know that the auction is sold out, and remove it from the page in real time. Imagine you have thousands connected users and hundreds auctions, how do you prevent the system from collapsing?
The answer is probably the bayeux protocol. There are several implementation out there, the one that I’m going to show you is Faye running over node.js.
Bayeux protocol allow us to create several channels where users can subscribe to, so we’re going to create a channel for each auction we’re running, each event we send to a single channel is propagated all over the other users. Please note, this is just an example and there are no security checks implemented, so don’t use that in the real world.
So, first of all we need to build up the server, this works fine (I assume you have node and faye already installed):

and run it as usual with: node bayeux_server.js
the default node server block is used to handle non bayeux requests.

Now we have to build the client, this is an example:

The channel subscription is made manually just to allow you understanding what’s happening. When you click ‘bid’ the message is sent to the server, and every browser with the page opened will receive the message for the subscribed auctions.

You can use both ruby and Faye on your server enviroment but just Faye for Rack.

How we do scrum

Software development can be a tricky process that often results in high overtimes, severe quality problems, constant firefighting, missed deadlines and sometimes even complete failures.  The 2009 CHAOS Report gives us a dramatic scenario of our work and reports that 24% of projects have completely failed.
Scrum is a methodology that should be flexible enough to be adapted to your specific situation, while drastically decreasing these common problems.

As an Agile method, scrum is based upon an iterative process and each iteration, also known as a “sprint”, should contain the three steps needed to improve how you would conduct a scrum:  observe, form a hypothesis, test it. Nothing more than a scientific method.

So this document describes how we do scrums today, but we can (and should) improve it again and again.  This is done during the Retrospective Meeting as described below.

Categories: Sviluppo Software Tags: , ,

Why work doesn’t happen at work

Italian Agile Day 2010 #iad10

Innanzitutto è la settima edizione della conferenza, significa che sono già 7 anni che qualcuno in Italia parla di queste cose (non so se il fatto che molti speaker siano italiani che lavorano all’estero sia significativo), e questo mi fa molto piacere, ho sempre visto l’Italia come la patria dei programmatori che “fanno FTP per incollare il codice sui file PHP in produzione“, oppure quelli della burocrazia sfrenata, dove una variazione all’analisi significa poi richiedere una nuova approvazione della stessa e nel caso ci sia un bando di mezzo non ne parliamo. Tuttavia eravamo circa 400 presenti, per la maggior parte giovani. Ecco un piccolo riassunto dei talk che ho seguito:

Keynote

L’introduzione all’evento è stata di Paolo Perrotta,  che è senza ombra di dubbio un oratore straordinario. Negli ultimi 30 anni in molti hanno cercato di paragonare l’ingegneria del software alle altre discipline (edile, meccanica ecc.) per risolvere quello che è un problema fondamentale, il suo elevato numero di insuccessi: il 24% dei progetti non viene alla luce, oltre il 70% subisce ritardi e variazioni di budget. Da molti anni qualcuno salta fuori dichiarando “la fine dei programmatori”, la tecnologia XY permetterà di realizzare software senza bisogno di programmatori, purtroppo (o per fortuna?) si tratta di tecnologie che puntualmente falliscono.

Read more…

delayed jobs

Vi sono alcuni casi in cui effettuare alcune operazioni direttamente da Rails prima della risposta di un controller richiederebbe troppo tempo. Si pensi ad esempio un processo che deve scaricare/caricare una risorsa esterna che potrebbe impiegare un tempo indefinito (ad esempio un feed RSS o un’immagine o l’invio di un’email), o effettuare un’elaborazione complessa, in questi casi l’utilizzo di una coda di processi permette di dare una risposta immediata all’utente e completare il task in background. Se necessario avvertire l’utente quando l’elaborazione è terminata è possibile utilizzare un polling ajax o comet (ad esempio APE) oppure quando disponibili sul client le websocket HTML5.

Vi sono diverse implementazioni di queue manager, da ActiveMQ a RabbitMQ (che è stato usato per forexdesk.com) alle innumerevoli versioni Java. La versione piu semplice che si possa adottare su rails, e sufficiente nella quasi totalità dei casi, è delayed jobs, da notare che questa soluzione è anche quella adottata da Heroku sui suoi workers.

JSON e JSONP con ruby on rails

JSON e JSONP sono molto spesso utilizzati da rails per dialogare con terze parti, ad esempio per rispondere a chiamate ajax. In rails vi sono diversi metodi per utilizzare JSON.
L’approccio old-school compatibile con rails 2.3 è quello di utilizzare il metodo respond_to e passare un blocco nel quale specificare i vari formati:

Con rails3 è possibile utilizzare il metodo respond_with:

Di default in rails include_root_in_json è true, in alcuni casi è necessario settarlo a false:

Per utilizzare JSONP è sufficiente specificare il metodo di callback nella render:

regexp in ruby1.9

Tra le novità di ruby1.9 ci sono alcune migliorie sulle espressioni regolari, oltre ad un significativo miglioramento nelle prestazioni, sono state introdotte due nuove funzionalità: look-behind e named captures.

Look Behind

look-ahead e look-behind sono asserzioni che non catturano l’elemento, ma controllano che intorno, rispettivamente davanti e dietro, sia presente o assente. Mentre look-ahead era già presente in ruby 1.8 la look-behind è stata introdotta con la 1.9. Per la look-behind positiva si utilizza la formula (?<=regex), la look-behind negativa invece (?<!regex). Di seguito due esempi, positivo e negativo, di look behind:

Named Capturing Groups

Named capture è una funzionalità a mio avviso molto rubish ed elegante, permette semplicemente di dare un nome alla capture, il nome sarà poi ovviamente la key nel MatchData. Per utilizzare la Named Capture si usa la sintassi (?<name>group). Di seguito un’esempio:

Se necessario utilizzare ruby 1.8 c’è a disposizione la gem di Oniguruma .

testare le routes con rspec2

Chi si è già aggiornato a rspec2 avrà notato che il vecchio approccio al testing delle routes è deprecato, il vecchio codice non funziona più:

it "should map { :controller => 'comments', :action => 'index' } to /comments" do
  route_for(:controller => "comments", :action => "index").should == "/comments"
end
it "should generate params { :controller => 'comments', action => 'index' } from GET /comments" do
  params_from(:get, "/comments").should == {:controller => "comments", :action => "index"}
end

C’è stato ultimamente un’interessante dibattito su quale sia la migliore via per procedere a questo tipo di test, nell’attesa che nuovo zucchero venga aggiunto (es: l’uso del nuovo formato di indirizzamento delle routes tipo “controller#action“) il nuovo approccio (che fa un check bidirezionale) è il seguente:

it "routes GET /post/:post_id/comments to comments#index for post_id" do
  {:get => "/post/1/comments"}.should route_to(:controller => "comments", :action => "index", :post_id => "1")
end

che però senza questo commit non funziona. Per procedere quindi è necessario al momento aggiornarsi all’ultima release di rspec-rails, modificando il file Gemfile:

group :test do
   gem 'rspec-rails',  :git=> "git://github.com/rspec/rspec-rails.git"
end

Patterns in Ruby: composite

Come nell’approccio olistico il pattern composite non fa altro che scomporre un problema in più parti elementari. Un’esempio può essere il calcolo delle dimensioni di una citta,  che è composta da case e quartieri: Read more…