Archive Page 2

Get all values of a single column efficiently

Imagine you want this:

@names = MyModel.find(:all).map{ |i| i.name }.uniq

Yes, that works! You get all distinct names of one column, you can even do something like that:

#Using Shortcut Blocks with Symbol to_proc
@names = MyModel.all.map(&:name).uniq

Cool, rely small code(almost seems I’m using Haskel) but not that efficient if your model’s table has lots of columns. (Imagine! The whole table is being loaded to memory) So what is the solution?

MyModel.find( :all, :select > 'DISTINCT name' )

If you specify wich columns you need, in the sql query, you will spare some memory. And in my earlier example you can also pass the “uniq” work to the database.

will_paginate without losing params

I’m sure you like will_paginate, it seams magic! But I was having the issue, that I simply solved like that:

will_paginate(@reports, :params => params.except(:page))

Rewrite humanize

I have an application with all tables and field names in English, but the whole views now need to be in Portuguese.

Because I’m always using the humanize method, a simple solutions should emerge.

First solution:

class Ticket
  HUMANIZED_ATTRIBUTES = {
    :category > "Categoria",
    :title > "Assunto"
  }
  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end
end


Setting the human_attribue_name in each model works ok,
but if like in my case, you have 20 models and all of them have a description, title,… much duplication…

So I thought in doing something similar to this in my enviroment.rb:

Inflector.inflections do |inflect|
  inflect.plural /^(foo)$/i, '\1ze'
  inflect.singular /^(foo)ze/i, '\1'
end


But for the humanized method instead of pluralize. Yah It would make sense that way, but rails doesn’t provide that feature. You can go here to find a patch for getting that functionality into your rails, I hope they get that into the core… anyway If didn’t want to download the patch, how do I solve the problem?

Maybe a rubbish solution but perfect to get what I was needing, translate my views with few lines of code!
What I’ve done? Just added those lines into my environment.rb

class String
  def humanize
    {:movie              => "Filme",
     :movies             => "Filmes",
     :name               => "Nome",
     :title              => "Título",
     :synopsis           => "Sinopse",
     :genre              => "Genero",
     :author             => "Autor",
     :authors            => "Autores"
     ...
    }[self.gsub(/_id$/, "").to_sym] || super
  end
end


I simply redefined the humanize method for whole strings. It works perfectly in my case, because I’m always calling humanize in my views.

keep humanizing the world!

Ruby on Rails no Ubuntu

As seguintes instruções demonstram como instalar o framework ruby on rails. Os comandos abaixo listados, foram por mim executadas exactamente após a instalação do Ubuntu 8.10.

Não deve ser necessário editar os repositórios. Mas fica o comando apenas para referencia.

sudo vim /etc/apt/sources.list

Pode pensar que full-upgrade inclui o safe-upgrade, mas é mentira são comandos diferentes. Portanto aconselho a intoduzir os dois pela seguinte ordem:

sudo aptitude safe-upgrade
sudo aptitude full-upgrade

Nesta fase é responder Yes a todas as perguntas!

sudo aptitude install build-essential

(Como disse estou a descrever os passos exactos que executei após a instalação do SO)
Agora sim vamos ao importante:

sudo aptitude install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl-ruby sqlite3 libsqlite3-ruby1.8

Criar alguns symlinks:

sudo ln -s /usr/bin/ruby1.8 /usr/bin/ruby
sudo ln -s /usr/bin/ri1.8 /usr/bin/ri
sudo ln -s /usr/bin/rdoc1.8 /usr/bin/rdoc
sudo ln -s /usr/bin/irb1.8 /usr/bin/irb

Agora vamos instalar o rubygems que nos oferece o comando gem, uma espécie de aptitude para o ruby.
Deve verificar qual a ultima versão de rubygems(http://rubyforge.org/projects/rubygems/), no caso de existir uma versão mais recente, substituir no comando em baixo.

wget http://rubyforge.org/frs/download.php/45905/rubygems-1.3.1.tgz
tar xzvf rubygems-1.3.1.tgz
cd rubygems-1.3.1
sudo ruby setup.rb

Criar symlink e garantir que temos o rubygems actualizado

sudo ln -s /usr/bin/gem1.8 /usr/bin/gem
sudo gem update
sudo gem update --system

E finalmente instalar o Ruby on Rails.

sudo gem install rails

Confirmar que tudo correu bem.
sudo gem list
Devemos obter uma lista deste genero:
*** LOCAL GEMS ***

actionmailer (2.2.2)
actionpack (2.2.2)
activerecord (2.2.2)
activeresource (2.2.2)
activesupport (2.2.2)
rails (2.2.2)
rake (0.8.3)

Verificar a operabilidade do sistema de base de dados sqlite:

irb
.......
irb(main):001:0> require 'sqlite3'
=> true
irb(main):002:0> exit

Para criar o primeiro projecto:

rails nome_do_meu_projecto

Já agora instalar o rmagick possivelmente tambem será util para a maioria dos projectos.

sudo aptitude install imagemagick
sudo aptitude install libmagick9-dev
sudo gem install rmagick

Agora é só por mãos a obra… e talvez arranjar um bom editor. Aconselho o textmate ou o vim, descreverei em breve como configurar e instalar alguns plugins para rails, no caso de escolher o vim.

How to Install Skype (Ubuntu)

Easy as it is. Just add the repository into your rep. list, update the package information and install Skype.

Open your list:

sudo vim /etc/apt/sources.list

Add this line at the end:

deb http://download.skype.com/linux/repos/debian/ stable non-free

Update:

sudo aptitude update

Install skype, answer yes to all question(but think for your self!)

sudo aptitude install skype

If you have some problems with audio(like I had) try this lines:


killall pulseaudio
sudo aptitude remove pulseaudio
sudo aptitude install esound
sudo rm /etc/X11/Xsession.d/70pulseaudio

(I’m using Ubuntu 8.10, but also works with Ubuntu 9.10)

Laurel and Hardy Archive Explained

A screencast showing some of the new laurelandhardyarchive.com feathers.

Awareness Test

Go here http://www.dothetest.co.uk/ to see the first one and some others!

PayPal Payments Standard, Subscriptions and IPN with Ruby on Rails.

Hi there!
 
I spend the last week struggling with PayPal documentations and with their buggy sandbox. The information is not well organized, and you can spend hours jumping between pages and pdf to find out what you want, I’m sure they like treasure hunt   games, I remember to following  10 steps, described on a pdf,  to download a sample code, (you should click this link, and now try to find a small square in the middle of the page, press it  and then you should close your eyes for about… crazy weirdoes) anyway… my goal was to implement a subscription system for laurelandhardyarchive, and of course because is subscriptions, with PayPal at UK, with IPN, and using rails, everything seems to be a little more difficult (only at the beginning ;) ), PayPal doesn’t provide any ruby samples, and there is a good plugin Active Merchant, but again because it’s subscription, the documentations also fails(not only for subscriptions, the whole Active Merchant  has a lack of documentation). With that scenario I figure out the best way to solve the problem was to build my own gem to deal with that, the gem should be finished soon, but anyway I leave you a small brief of what is needed to accomplish this, and I leave you some links, so that way you don’t need to a treasure hunt throw PayPal web site.
 
So… do you need to integrate PayPal subscriptions and IPN into your web site?
 
For starting you should register into developer PayPal then you should create two sandbox PayPal  accounts to do your tests (you can use the preconfigured account button for those, but be aware to chose country US even if you are in UK, because you will have troubles to activate the test account, but don’t worry you real account should not have any problems based in the country),  one of the account should be busyness type and the other personal type account, you will use them  to simulate the seller and buyer roles, don’t forget to start the personal account (the buyers one) with some money(fake money) you can do that while creating it, click the advanced otptions drop down.
 
So right now you can use your business account to create code for subscription buttons. For doing that you should access PayPal sandbox, in the developers page (when listing the accounts) you have a link for that. PayPal sandbox is a complete copy of the original PayPal web site, and all test accounts can interact in this closed world.
 
This is all for now. I’ll try to post some code latter. In any case if you’re trying to achive something similar and having some difficulties, leave me a message, if have the knowledge to I be glade to help.

E o semestre acabou!

Viva! Antes de mais gostaria de pedir as mais humildes desculpas às largas centenas de pessoas que nos últimos dois meses tem visitado o meu blog na esperança de algo novo… Humm…  Eu admito, não são centenas, são apenas de dezenas… Pronto às vezes chega a ter uma dezena…  mas é uma dezena larga, e é gente interessante por isso merece este pedido de desculpas.

Estive, estes últimos dois meses, ocupadíssimo com trabalhos e exames. Bolonha veio alterar completamente o ritmo de trabalho, pelo menos na Universidade do Minho. Não digo que seja injusto ter-mos mais trabalho, há muita coisa que estava mal e que me parece poder beneficiar com Bolonha caso esta seja executada convenientemente. Tenho a sensação que ainda ninguém está habituado a esta nova etapa. É normal surgirem complicações num período de adaptação… Aguardo então ansiosamente pelo próximo semestre, e espero que desta vez as coisas corram melhor e não cheguemos ao fim com uma semana para entregar trabalhos, fazer “testes” (testes esses que na verdade são os exames que antes estavam espalhados ao longo de um mes) e tudo isto com extrema falta de coordenação (pelo menos foi isto que se passou no meu curso, LESI ou LEI) pois nem se sabia ao certo datas, horas, salas disponíveis para os exames etc… Acredito que tenha servido de lição, e espero por algo melhor ao longo dos próximos meses!

De qualquer forma terminou o semestre e estas cadeiras já estão todas feitas.=)

Ao longo destes dois meses, e enquanto fazia alguns destes trabalhos tb tive oportunidade para aprofundar os meus conhecimentos de RoR (Ruby on Rails)por sinal uma Framework muito interessante. Espero, agora que a tempestade passou, poder voltar a escrever algo neste blog e tecer alguns comentários por exemplo acerca de algumas cabeçadas que dei no rails ao longo do trabalho de BD!

VIM for beginners

The first time I saw vi text editor was when I reaches university, it seemed a little bit counterintuitive at the time. I think it is a normal feeling to new vi users, even more, if you are, like I was, used to Windows and GUIs but make no mistake, there is a good reason for this 30-year old tool still be widely used by many of the best developers in the world. A few days ago I was programming some rails application, and while doing some changes in a few files with vi editor I realized I couldn’t take full advantage of vi and do what I saw my teachers doing like !indenting! a text with few keyboard shortcuts, so, I spend two hours reading the vim help and I realized how fantastic vim is! Now if you wanna try vi I will give some little tips, like a mini tutorial for vi/vim beginners.

For showing you the shortcuts I’ll use a similar notation to the used on vim help.
<ESC><CTRL-v>5jI
This means you press ESC key then you press Ctrl and “v” key simultaneous then you press the number 5 followed by the “j” key and finally you press “I”. I think you can get the idea. If you can’t, vim isn’t for you or I’m worst teaching then writing English!

Ahhh… Another thing, Vim has something similar to a command line, when you do this <ESC>: you will start writing commands at the bottom of the screen for example, :q is for quitting the program. Of course when I say something started with “:” like “:q” I’m expecting you to write that on the command line, not in your text, so if you are in insert mode you have to do something like this <ESC>:q<ENTER>
Well… now when talked about insert mode I introduced one more thing; the vi working modes! When using vi you can switch between different working modes, for example to insert text you should be on INSERT MODE, when selecting text you are on SELECTION MODE, you have also REPLACE MODE, VISUAL MODE, and more. Those operating modes give you ultrafast access to key commands that can edit, insert, and move text in on-the-fly…

Here are some examples of commands:

Calling VIM:

Vi Open vim with no file.
vi PATH Open PATH file with vim, if the file doesn’t exist create it.
vi PATH + Open the PATH file and focus cursor at end of file.
vi PATH +10 Open file at line 10.
vi PATH +/regedor Open file with courser at the first occurrence of the word “regedor”

Saving/Quitting VIM:

:w Save
:q Exit without saving
:wq or : x or ZZ Exit and save
:w! Force Save
:q! Force Quit
:wq! Force Save and Quit

Well this is good for beginners. But for now I don’t have more time, I will set up a more complex tutorial with a few more advanced commands soon.

« Previous PageNext Page »


Last Regedor’s twitts

Last Regedor's bookmarks