nunojob:~ dscape/08$ echo The Black Sheep

Archive for the ‘Projects’ Category

RSA Encrypt & Decrypt in ruby

Well I finished the encrypt with RSA on ruby some hours ago and felt like sharing :)

Case you feel like doing something back for me just download the latest release of my beta twitter client and send me some comments to my email. It’s pretty hard to test something when my environment is completely contaminated !

require 'openssl'
require 'Base64'

class Rudolph
  class Crypt
    def initialize data_path
      @data_path = data_path
      @private   = get_key 'id_rsa'
      @public    = get_key 'id_rsa.pub'
    end

    def encrypt_string message
      Base64::encode64(@public.public_encrypt(message)).rstrip
    end

    def decrypt_string message
      @private.private_decrypt Base64::decode64(message)
    end

    def self.generate_keys data_path
      rsa_path = File.join(data_path, 'rsa')
      privkey  = File.join(rsa_path, 'id_rsa')
      pubkey   = File.join(rsa_path, 'id_rsa.pub')
      unless File.exists?(privkey) || File.exists?(pubkey)
        keypair  = OpenSSL::PKey::RSA.generate(1024)
        Dir.mkdir(rsa_path) unless File.exist?(rsa_path)
        File.open(privkey, 'w') { |f| f.write keypair.to_pem } unless File.exists? privkey
        File.open(pubkey, 'w') { |f| f.write keypair.public_key.to_pem } unless File.exists? pubkey
      end
    end

    private
    def get_key filename
      OpenSSL::PKey::RSA.new File.read(File.join(@data_path, 'rsa', filename))
    end
  end
end
Advertisements

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)

Yet Another Ruby on Rails Web Application – Teaser

Integração entre RSpec & TextMate

Como já disse anteriormente ando a trabalhar no CouchDB-Ruby driver. Como a coisa tem o seu nível de exigência decidi usar rspec, algo que já andava para fazer a algum tempo, de forma a melhorar a testagem do software que produzo e reduzir o tempo de implementação. Já agora aproveito para sugerir o ZenTest a quem quiser que o rspec corra em background.

Continuando: rspec é uma forma descritiva – tipo cenários em Use Case – para descrever os nossos testes. Em Ruby claro, dai o R :P

O resultado final fica assim. É catita e prático, já que evita mais uma ida a consola para escrever ‘spec filename.rb’! E é bastante parecida com a linguagem natural. Por exemplo – um dos meus primeiros testes é:

it "should connect to server and return a Server object" do
  CouchDB.connect(HOST, PORT).should 
    be_kind_of(CouchDB::Server)
end

Não fiz commit de nada porque a implementaçao anterior do CouchDB-Ruby com JSON não está completa. Portanto não vale a pena ir espreitar que não está nada lá! Em breve, espero eu, podem ver os testes completos online.

De qualquer forma se estiverem interessados em experimentar o rspec basta:

  • Instalar o rspec
    sudo gem install rspec
  • Descobrir o path onde está o ruby e o rspec. Estes comandos são capazes de ajudar:
    which ruby
    gem environment
  • Com os meus paths basta correr:
    export TM_RUBY=/usr/bin/ruby
    export TM_RSPEC_HOME=/Library/Ruby/Gems/1.8/gems/rspec-1.1.3
    cd ~/Library/Application\ Support/TextMate/Bundles/
    svn co svn://rubyforge.org/var/svn/rspec/trunk/RSpec.tmbundle
    
  • Como o (meu) terminal não gosta de exports. Caso não funcione façam:
    echo TM_RUBY=/usr/bin/ruby >> ~/.profile
    echo TM_RSPEC_HOME=/Library/Ruby/Gems/1.8/gems/rspec-1.1.3 >> ~/.profile
    
  • Actualizar os Bundles do TextMate
    Bundles > Bundle Editor > Reload Bundles

E pronto! Caso surjam dúvidas podem sempre consultar a documentação oficial do bundle rspec para TextMate. Que comece a diversão! Bem vá diversão é exagerar mas com rspec é pelo menos uma experiência mais agradável que o habitual quando se fala de testes.

Random in Ruby on Rails

So your doing a find on your model and you want a random instance. I didn’t find a method to do this so I decided to make my own.

In this case I wanted a random quote. So after generating the model all I had to do was:

def self.random
  Quote.find_by_id rand(Quote.count) + 1
end

And now you can simply call your random quotes in any controller action you desire. Just

@rquote = Quote.random

If this is the lamest ruby ever please feel free to give me some feedback :) I will be delighted to learn a different way!

[EDIT: Discussion about this at Rails Core]

This version of RMagick was created to run with ImageMagick 6.3.3 but ImageMagick 6.3.8 is in use

A paciencia tem os seus limites e vou dormir. Se entretanto alguém descobrir a solução para isto peço-lhe o favor de me deixar nos comentários.

xForms Example (CSS)

Sample Xforms Application using cssSo here comes my first ever XForms sample. If you are interested in testing them out I’ll have to give you some pointers. First off all your browser probably can’t render XForms. So you need to find a specific add-on for your browser to make it work. As this XForms where made in Mozilla Firefox with this add-on I strongly recommend that you use it to get the same results. This is not my fault, XForms is not as mature as HTML or CSS and therefor these things tend to happen. You will see what I’m talking about when I get to the Know Issues! :PNow two short notes:

  • For the load/save button to work you will need to change the path in the code. Just look for xforms:submission and replace the filepath for the one in your computer.
  • You need to comment what’s between this for the load button to work. Why? The bind is interfering with the instance replace. How do you fix it? If i knew I would have. I think that when I do remove the bind and add the schema this behavior will be fixed..

<!– remove this lines to erase load bug. Using a schema will fix this –><!– EOB: End of bug –>

Credits for the icons go to famfamfam.Here is the list of known issues (any help is welcome):

  • Not binded to the schema. That’s because I’m lasy and METS is hard work.
  • xforms:select1 won’t hide the scroll on overflow:hidden. I’m not sure this is my responsibility as the add-on doesn’t represent a full XForms implementation.
  • Submission not implemented. That was really not the point.
  • Submission button is relevant when no authorid or workid is given. Anyone?
  • Can’t style ‘add’ and ‘remove’ trigger differently from the other xforms|trigger. I tried creating a class for them having as result a weird inverted triagle. To replicate this bug you need to find a trigger and add style=”border:100px;”.

For now: that’s all folks! Have a nice week.