nunojob:~ dscape/08$ echo The Black Sheep

Posts tagged ‘Ruby on Rails’

Open Source Online Testing System (OSOTS)

I simply can’t believe that I forgot to post this project in my blog. Anyway if you have to deploy a multiple choice test and you feel like messing arround with Ruby on Rails and DB2 here goes the link.

Open Source Online Testing System (OSOTS)

Information Retrieval using the Boolean Model in Ruby on Rails

DB2 Rocks

qs = Question.find_by_sql 
"select X.* from ots_schema.questions," +
  "XMLTABLE (\'$d/question\' passing document as \"d\" " + 
    "COLUMNS question_text VARCHAR(200)" + 
    "PATH \'question_text\') as X"
qs.first.question_text.lstrip
=> "Which of the following is the correct syntax to set the DB2COMM variable to TCPIP?\n  "

If DB2 was had a good DB2 driver and a ActivePureXML (or something adapter) it would so f*ckin rock. Just look at the sample. And the dynamic nature of ruby would enable the flexibility of xml documents.

Please IBM please. DB2 for mac and decent support on Ruby. Don’t make me write things like this no more:

# Once again fixing IBM_DB bugs the ugly way
# with_scope anyone?
add_index :'ots_schema.users', :login

or

t.column :document, :xml

CouchDB & Um Novo Semestre!

Bem todos os semestres faço um plano de acção do que vou fazer para além de o que é espectável de mim – ir as aulas, fazer os trabalhos, passar nos exames e ler pelo menos um livro de informática – de escolha livre – por mês.

Acredito na valorização pessoal e gosto muito de aprender coisas novas. E acredito que não existe melhor forma de o fazer que com projectos práticos!

Algumas das novidades do último semestre foram ter entrado no centro de apoio ao open-source do departamento de informática, ser eleito IBM DB2 Student Ambassador e ter entrado na melhor rede de bloggers de informática de portugal – prt.sc. Como projecto pessoal escolhi aprender – por sugestão do Ulisses CostaRuby & Ruby on Rails.

Dito isto resta uma dúvida: O que aprender este semestre?

Tenho que confessar que ando nas nuvens por terem aceite a minha colaboração no projecto CouchDB do rubyforge.

Como devem saber CouchDB é uma base de dados criada pelo Damien Katz (que trabalha agora na IBM), não relacional, desenvolvida em erlang que tem como objectivo guardar documentos e é RESTful. Os conceitos são excelentes e a forma de abordar o fault-tolerance e problemas de carga são daqueles conceitos que nos deixam a babar mortinhos por experimentar o brinquedo novo. Mas não se fica por aqui. Aconselho a lerem a wiki para terem uma noção do que é – e o que não é – o CouchDB. Só não gosto muito do facto de estar tão ligado a javascript e JSON – o primeiro porque nunca gostei muito de javascript e o segundo porque preferia yaml. Mas vá antes JSON que XML!

Outros tópicos que andam por aqui a passear – sendo que aqui é a minha cabeça – é a vontade de aprender um mínimo de Erlang e continuar o estudo de DB2 para tirar a certificação. Espero que quando acabar este semestre possa olhar para trás e sentir a mesma satisfação que sinto pelo semestre que já passou.

METS Standard with IBM DB2 Express C using XForms as user-interface and Ruby on Rails as a Rest Web-services

HIGH QUALITY VERSION DOWNLOAD HERE

Well, here is the long promised screen-cast. The amount of topics covered is simply huge. To get you ready for the screen-cast I prepared some other more introductory screen-cast as well as some articles on these subjects. I’m sorry that I don’t have the time to document the REST, but I really advice to invest some time learning it as it’s a very pragmatic way of delivering high quality web services.

I strongly advice you to download this screen-cast from rapidshare as both Youtube and Google Videos quality is really awful. You can download it from here.

This work was really fun to do. So I hope to have the opportunity to develop it further and manage nested rest routes like /mets/1/agents to return the agents of the first submission information package (sip) using some cool DB2 pureXML features. I really feel that with a good plugin to help users take full advantage of DB2 pureXML features and a little of imagination this web-service could be of some use.

I also expect to complete the xforms model as it is not indexing a fileptr to each category when such is selected. I hope to implement this soon enough.

Here are the associated resources I developed:

And here are the other two screencasts I produced to introduce you to XForms and METS:

I also advice you to take a look at this articles. All of them where very helpful to my work.

XmlSimple?

>> xml_plain = %q(<p>Just a <strong>p</strong> on bold</p>)
=> "<p>Just a <strong>p</strong> on bold</p>"
>> xml_hash = XmlSimple.xml_in xml_plain,
  'ForceArray' => true
=> {"strong"=>["p"], "content"=>["Just a ", " on bold"]}
>> xml_plain2 = XmlSimple.xml_out xml_hash, 
  'RootName' => 'p'
=> "<p>\n  <strong>p</strong>\n  <content>Just a </content>\n  <content> on bold</content>\n</p>\n"

Não querendo ser malvado com quem fez esta biblioteca acho que o mínimo expectável para uma operação de marshall/unmarshall é que seja reflexiva. Lá vou eu ler documentação para descobrir como se ensina o XMLSimple – nome curioso não é? – a ser o que nunca deveria deixar de ser. Reflexivo.

Já agora se alguém já programou web services em rails e sabe como transformar os params em xml de uma forma melhor, let me know!

Devolvam as passwords aos vossos utilizadores com Ruby on Rails 2.0

Uma coisa que me chateia imenso nas webapplications de trazer por casa – traduzindo aquelas que são feitas por colegas meus ou por outros amadores pela web fora – é o facto de guardarem quase sempre as passwords na base de dados em plaintext. Acho que não tem o direito de saber a password que uso, nem que a use exclusivamente nesse site (como é o caso)

Assim, se quem fez a aplicação for mal intencionado, pode simplesmente obter a vossa password escrevendo

select * from users where user.username = 'nick'

Mas mesmo que não sejam mal intencionados, outra pessoa pode aceder a base de dados. Ou podem simplesmente não se ter protegido contra sql injection. Há um milhão de razões pelas quais nunca se deve guardar as password em plaintext, sendo que a principal deles é o facto da password não ser vossa. É do utilizador. E isso faz toda a diferença! Não acreditam em mim certo? Estou a exagerar.

Convido-os a visitar esta página

Agora procurem por ‘qualquer_coisa. O resultado é

  • Pesquisa por “\’qualquer_coisa”:

Este \’ é importantíssimo pois significa que a página se esta a proteger contra ataques de sql injection. Caso contrario um hacker podia, com alguma sorte, obter informação privilegiada que estava contida nessa base de dados.

Mas ninguém faz um erro destes, certo? Errado. Vamos ao google e procurem php em páginas de Portugal. O sexto resultado, e único que testei, é a associação nacional de farmácias. Se procurarem por ‘qualquer_coisa o resultado é um não tão surpreendente erro. Isto é um exemplo de milhares, alguns dos quais onde vocês inserem as vossa password (e sabe-se lá o que mais) diariamente. Não se sentiam melhor se soubessem que nessa base de dados não está a vossa password?

Mas voltando ao assunto, a táctica que vou usar consiste em usar um algoritmo de one way hash chamado SHA. O utilizador, quando se regista no site, insere a sua password. Esta é processada (num processo que se chama de digest) para uma hash que contém não a password mas sim a encriptação dessa password em SHA. Como SHA é um algoritmo de one-way-hash, é fácil obter a hash única para qualquer palavra mas quase impossível de decifrar no sentido inverso. Para ser suficiente, mas não é.

Comecemos por ir para a consola do rails. Entrem no terminal e naveguem até onde tem a vossa Ruby on Rails web application. Agora escrevam.

./script/console

Quando lá estiverem podem verificar que aplicando este algoritmo a palavra porto obtemos sempre a mesma resposta.

>> password = 'porto'
=> "porto"
>> Digest::SHA256.hexdigest(password)
=> "01735c5ff1608734e4c38449a00b74bb9a8d5423ed548238da70178e9e803483"
>> Digest::SHA256.hexdigest(password)
=> "01735c5ff1608734e4c38449a00b74bb9a8d5423ed548238da70178e9e803483"

Não sei se repararam mas o nosso utilizador usa uma palavra pass muito fraca. Isto vai fazer a diferença, por o hacker pode obter a password facilmente se tiver a hash.

Como? Sim eu disse que era muito difícil crackar o SHA, alias não conheço ninguém que o tenha feito. Ninguém conhece :P

Mas o hacker pode pegar numa lista de palavras comuns nas passwords e, para cada uma das palavras associar a hash correspondente. Agora se tiver a vossa hash pode comparar com o dicionário que criou descobrir algumas das passwords da base de dados, aquelas que estavam na lista de palavras comuns.

Para resolver este problema usamos um salt. Um salt é também uma palavra (como a vossa password) que sera usada para evitar esta técnica. é mais simples mostrar que explicar, e por isso mesmo:

>> password = 'porto'
salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
>> salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
=> "19L6gVcD"
>> salt = [Array.new(6){rand(256).chr}.join].pack("m").chomp
=> "CqEVe632"
>> password = 'porto'
=> "porto"
>> Digest::SHA256.hexdigest(password + salt)
=> "c017e1c49096149097050c76f0406dce9245058e0d..."

De certeza que o hacker não vai procurar pela string portoCqEVe632 e, portanto, os nossos utilizadores estão seguros. Caso queiram saber um pouco mais sobre o que se passa no criação do salt, e que é aquele pack(‘m’) peçam nos comentários e eu escrevo um artigo sobre isso. Senão nunca mais saio daqui! :P.

Agora surge a pergunta, como usar esta informação em rails. Simples.

Vamos começar por criar um projecto:

rails secureusers && cd secureusers

Agora precisamos de criar o modelo de utilizador

./script/generate model User username:string \
  password_hash:string password_salt:string
rake db:migrate

Abram o vosso User.rb model, apaguem o que lá tem, e insiram o seguinte código

require 'digest/sha2'
class User < ActiveRecord::Base
# usei o attr_accessible em vez do
# attr_protected :password_hash, :password_salt
# porque é boa prática em Rails usar o enabled para 
# os campos acessíveis e não o contrário.
#
# Imaginem que tinham um campo isAdmin e se 
# esqueciam de por no protected.
# Ao dizerem que enabled só o :username impedem 
# o acesso a todo e qualquer outro campo,
# excepto aqueles que foram explicitamente 
# escolhidos por vocês.
  attr_accessible :username
  attr_accessor :password

  def before_save
    unless password.blank?
      salt = &#91;Array.new(6){rand(256).chr}.join&#93;.pack("m").chomp
      self.password_salt, self.password_hash = salt,
      Digest::SHA256.hexdigest(password + salt)
    end
  end

  def self.authenticate(username, password)
    user = User.find :first,
        :conditions => ['username = ?', username])
      if user.blank?
        raise "O utilizador não existe"
      elsif Digest::SHA256.hexdigest(password + user.password_salt) != user.password_hash
        raise "A autenticação falhou"
      else
        user
      end
  end
end

Usei o attr_accessible em vez do protected porque considero esta uma boa practica. Prefiro dizer quais os campos acessíveis que quais os que se deve proteger. Assim não corro o risco de me esquecer de proteger algum campo. E os que são para ver nota-se bem quando faltam :P Podem ler mais sobre isto aqui.

Depois de toda esta explicação o código deve ser muito facil de entender. Até para quem não sabe Ruby. Vamos testar?

>> nuno = User.new
=> #<user id: nil,
  username: nil,
  password_hash: nil,
  password_salt: nil,
  created_at: nil,
  updated_at: nil>
>> nuno.username = 'nuno'
=> "nuno"
>> nuno.password = 'porto'
=> "porto"
>> nuno.save
=> true
>> nuno
=> #</user><user id: 1, 
  username: "nuno",
  password_hash: "c490ea11d96be24ece2ca0dba11d84fc9b...",
  password_salt: "V+b7Sqjh",
  created_at: "2008-02-12 19:28:54",
  updated_at: "2008-02-12 19:28:54">

E agora autenticar:

User.authenticate 'nuno', 'porto'
=> #</user><user id: 1, 
  username: "nuno",
  password_hash: "c490ea11d96be24ece2ca0dba11d84fc9b...",
  password_salt: "V+b7Sqjh",
  created_at: "2008-02-12 19:28:54",
  updated_at: "2008-02-12 19:28:54">

Fixe. É so por no session[:user] ;) Para finalizar aconselho-vos vivamente a suportarem open-id para o processo de autenticação dos utilizadores. Existem plugins muito bons que o fazem, e podem ler mais sobre open-id no seu fantástico guia supersónico.

e-archia.net

Bem a minha primeira aventura em rails chegou a metade. Quem estiver interessado em ver as sources, pode sacar este não-tão-pequeno ficheiro. Senão fica aqui a screenshot. O site não está online porque eu, com a pressa, não tenho a certeza ser fiz escapeHTML ao texto que vem da base de dados. Ficam as screenshots:

Crescimento do emprego em Ruby

As coisas em Portugal costumam demorar a chegar ao ponto que estão nos states. Basta ver que a maioria das propostas que vejo por cá são em Visual Basic (hein?). De qualquer forma convido-os a ver estes gráficos a tirarem as vossas próprias ilações:

Ruby, Java ou C#?

Ruby on Rails, PHP ou ASP.NET?

Será que alguma vez as empresas de portugal iram estar um passo a frente em vez de vinte passos atrás? Não me parece mas, uma pessoa pode sempre sonhar!

The Rails Way

Livro novo para ler. Darei feedback quando acabar, estou bastante feliz por ter a oportunidade de o ler!

Rails is more than programming framework for creating web applications. It’s also a frame-work for thinking about web applications. It ships not as a blank slate equally tolerant of every kind of expression. On the contrary, it trades that flexibility for the convenience of “what most people need most of the time to do most things.” It’s a designer straightjacket that sets you free from focusing on the things that just don’t matter and focuses your attention on the stuff that does.
To be able to accept that trade, you need to understand not just how to do something in
Rails, but also why it’s done like that. Only by understanding the why will you be able to consistently work with the framework instead of against it. It doesn’t mean that you’ll always have to agree with a certain choice, but you will need to agree to the overachieving principle of
conventions. You have to learn to relax and let go of your attachment to personal idiosyncrasies when the productivity rewards are right.

Skitchcast: Ruby Gems is now on v1.0

Here how to update your gem to 1.0 and RoR to 2.0.2

From Ubuntu/Windows to Mac OS-X Leopard

I just got my first brand new MacBook and, as one would expect, some problems emerged by leaving my usual OS combo (Ubuntu/Windows) for Mac OS X Leopard. I’m still undecided whether to install Ubuntu or use VMWare Fusion to use Linux. As for Microsoft Windows as long as I don’t need to use .NET I don’t think I’ll install it. Not even with the free licenses Microsoft provides University of Minho students.

First I had to decide what to install:

The question you are probably asking is why Firefox instead of Safari!? Because the damn unsafe add-on for del.icio.us is just that: del.icio.us! I just can’t live without it. Maybe if the guys over there worked the basics of security we could say that it’s both excellent and safe! And don’t say there’s a add-on for Safari as well. I’ll only accept it if the add-on is as good as the one provided by Yahoo.

Now we go for the fun part. The problems and solving them. Your attention please, this is only fun for me when I do it on my computer so it won’t be pleasure if you ask me to fix your computer! Joana this one is for you, I know how your mind thinks.. Almost as badly as mine. Oh well, we are related aren’t we? :\ Please release those crazy Christmas photos to the world! :X

I’ll start with a small OS free tip and then go for the Q/A part. If you are Portuguese like myself you just hate all the results that google gives you from .br domains. Most of the results are overrated and most of the times you just wish that they weren’t there. If this is the case just do your normal search in google but write -br in the end. Just test this, go to google and type governo brasileiro -br. It works ;)

  1. How do I get my mouse to behave like a normal one by removing this dreadful acceleration?

    Easy. Check Rúben’s blog @ http://blog.0x82.com/2007/12/mac-os-and-usb-mouse.html

  2. What’s wrong with the encoding on TextEdit? The automatic descovery does not work and even when I specifically tell him to use this encoding it won’t work. The Where is ISO 8859-15 dilemma.

    Still don’t know. Anyone? If you want to test the bug just do this (from here):

    $ echo é > ~/a.txt
    $ cat ~/a.txt
    é
    Open a.txt with TextEdit and get:
    È

    Cracked it! At least I have a partial fix for Migrating documents from Ubuntu to Mac OS X Leopard:

    cmd + space terminal enter

    {go to the directory where the file is}

    bash$ iconv -f ISO-8859-15 -t UTF-8 {filename} > UTF8-{filename}

    For me it was:

    bash$ iconv -f ISO-8859-15 -t UTF-8 Pam.tex > UTF8-Pam.tex

    And yes PAM is as in Pluggable Authentication Modules. So I have a latex work on that :P

    
    
  3. Where is type-a-name application? It’s not on the dock.

    Just press cmd + space and type what you are looking for. This is called spotlight. Either this or open Finder and go to applications.

  4. Why doesn’t it show my dashboard when I go to the left/whatever corner?

    Have you even configured your mac? Common.. Click the apple on the top left corner and go to System Preferences. Exposé and Spaces. And now that you are there take a look around and configure all the other things that you neglected.

  5. This computer is always underlining the words in red. (when the spelling is right :P If not you are a dumbass for asking this!)

    Just press cmd + mouse and change the language. Thanks Nuno Veloso from Apple Tech Team for this tip.

  6. How can I see the right mouse button menu?

    crtl + mouseclick

  7. PageUp/PageDown!?

    fn+ up
    fn + down

If after this you still feel like reading about Mac OS for rookies – like myself – you can check this section in Arun Gupta’s Blog or check this extensive list of Keyboard Shortcuts. Have fun!

Now let’s get back to work, something almost impossible when your doing a report on LaTeX and the encodings are never right.

One final touch: ctrl + alt + cmd + 8. Merry Christmas! :)

Ruby on Rails vs Java

Netbeans 6 RC2 Uninstallation Issue

Well i have been using Netbeans IDE Beta 1 for some time now.

I was using it to develop some Ruby on Rails projects. Some days ago I was in cryptography classes and tried to use the Apache Tomcat support for the Netbeans Beta 1. As I found out there was some bug in my way I decided to download the new RC2 and see if the issue got fixed in the meanwhile.

That when I first tried to uninstall Netbeans Beta 1. I got this error and still don’t know how to fix it. So I submitted it to Netbeans Community as a bug.

Anyone with the same problem got it fixed?

[UPDATE: Solution here]

I know that I have recently said that Netbeans has the best support to work on Ruby on Rails. It does. But just don’t use the beta. It’s crappy. If your on 512mb of RAM like me your computer will hate Netbeans Beta. I don’t even know if they will ever get this fixed. (Maybe a lightweight version of Netbeans is in order)

Is there such thing as the perfect IDE? We should be focusing on developing not on the IDE.

DB2 Express-C 9.5 Released

A new version of DB2 Express-C was made available by IBM today. As you might already know DB2 Express-C is a free dataserver without limits on database size or number of users.

We got this news from

You won’t find this new version on IBM DB2 Express-C Website, but you can download the Linux Version here and the Windows Version here.Mac version is still not available. This is probably the down side as many of us are waiting for IBM to ship a Express-C DB2 version for Macintosh. Hopefully next time?

I still didn’t tested the new DB2 but according to Antonio

Version 9.5 brings to the table a great deal of new enhancements and features. Among these there is also the reduced amount of memory requirements and the improved efficiency of operations on Linux. Oh and it will also make you rich and more beautiful. I mean, pureXML support has been greatly improved and it is a release that is sure to please many people on both Windows and Linux.

I know the t-shirt looks great. Hopefully Vítor will send me one! :P

Learning Rails

TestsDamn I HATE TESTS. Unit testing is boring…
Learning rails is hard. I know it’s supposed to be easy to use. And it is.

But if you explore it a little further, and you want to know how things work, properly understand the framework and language than your in trouble. And you’ll have some headaches with it, specially on the damn tests. Knowing that in some two months I’ll have enough knowledge to create a web application is what keep me going…

When I’m done with the first study, I’ll let you all know what my impressions where. For now I’ll describe Rails framework as highly impressive and simple, but different from all you have seen before.

Some advices to who is starting, use Netbeans 6.0 and InstantRails. Visit Netbeans Documentation for quick tutorials and read the book I referred to in another post for more advanced topics.

7 tests, 7 assertions, 0 failures, 0 errors
6 tests, 12 assertions, 0 failures, 0 errors

I’m out of here.

De volta aos carris

Estou a ler o livro Ruby in a nutshell do Yukihiro que é um dos dois únicos livros que a biblioteca da minha universidade tem sobre Ruby mas, infelizmente, não se apropria a um iniciante como eu. Então andava a aprender pelo help. Não acredito nessa do estuda rails e aprende assim Ruby.

A linguagem primeiro, a framework depois.

Só que existe um pequeno problema. Na biblioteca da Universidade do Minho existem tantos livros sobre Ajax como livros sobre Rails. ZERO!

Por sorte andava por entre o Twitter e o greader quando encontrei um livro para iniciantes em rails de graça! Nos próximos 58 dias quem quiser o livro Build Your Own Ruby on Rails Web Applications pode sacar-lo AQUI. Claro que a oferta apenas vale alguma coisa se o livro tivesse qualidade mas, ao que parece, tem. Pelo menos a ver pelas reviews que andei a ler.

OFF-TOPIC: Quem achar giro programar direct3D em .NET pode ler uma iniciação neste artigo.

UPDATE: Já estou a ler o livro e aviso desde já que a parte que ensina Ruby e OOP está medíocre. Leiam algo sobre Ruby antes de lerem este livro!

Life on the rails

I found Ruby in a talk with one of my friends. We were talking about how a problem that can be solved in Haskell in one line of code, could take hundreds to do so in Java or C#. It was obvious that, for some specific problems, Haskell was simpler and adequate.

Want a sample? Code permutation with n levels in C.

perms xs 0 = [[]]
perms xs n = [ p : ps | p <- xs, ps <- perms xs (n – 1)]

And like this he introduced me to Ruby on Rails. I was very thrilled to see a language that is dynamic, object oriented and adequate for web developing. I immediately thought about learning it, I just love learning new languages.

Today I checking my feeds and found a post about seven reasons to switch back to PHP (from Ruby).

It seems Ruby is like Haskell: the code looks greats and promises a lot, but it still doesn’t get where imperative languages do. (I’m still going to learn it, I just can’t resist it)

For now I’m waiting for a language that joins all that is good from imperative, functional, logic and object oriented paradigms.

If you know such programming language leave it as a comment.

 

 

PHP $61,000

 

Ajax $76,000

 

Ruby $70,000

 

Java $77,000

 

C# $78,000

 

Haskell $52,000

 

View Larger Salary Graph