Tag Archives: ruby

Screencasts de Ruby on Rails para iniciantes

ruby_rails

No ano passado, eu comecei a gravar alguns vídeos pra ajudar quem gostaria de começar a programar com Ruby on Rails.

Por enquanto são 3 screencasts apenas, mas já é o suficiente pra quem gostaria de começar.


Linguagem de programação “Ruby” (para iniciantes)



Ruby on Rails (para iniciantes)



Ruby on Rails – introdução às rotas


Por favor, me mandem feedback, com sugestões, críticas ou até mesmo dúvidas. Espero que gostem e que seja útil ;-)

Interesting script written in Ruby: “The Globe”

Minutes ago I received this link from some friends. It’s very interesting (and crazy).

Create an empty ruby file, paste this content and save as a.rb.

v=0000;eval$s=%q~d=%!^Lcf<LK8,                  _@7gj*LJ=c5nM)Tp1g0%Xv.,S[<>YoP
4ZojjV)O>qIH1/n[|2yE[>:ieC       "%.#%  :::##"       97N-A&Kj_K_><wS5rtWk@*a+Y5
yH?b[F^e7C/56j|pmRe+:)B     "##%      ::##########"     O98(Zh)'Iof*nm.,$C5Nyt=
PPu01Avw^<IiQ=5$'D-y?    "##:         ###############"    g6`YT+qLw9k^ch|K'),tc
6ygIL8xI#LNz3v}T=4W    "#            #.   .####:#######"    lL27FZ0ij)7TQCI)P7u
}RT5-iJbbG5P-DHB<.   "              ##### # :############"   R,YvZ_rnv6ky-G+4U'
$*are@b4U351Q-ug5   "              #######################"   00x8RR%`Om7VDp4M5
PFixrPvl&<p[]1IJ   "              ############:####  %#####"   EGgDt8Lm#;bc4zS^
y]0`_PstfUxOC(q   "              .#############:##%   .##  ."   /,}.YOIFj(k&q_V
zcaAi?]^lCVYp!;  " %%            .################.     #.   "  ;s="v=%04o;ev"%
(;v=(v-($*+[45,  ":####:          :##############%       :   "  ])[n=0].to_i;)%
360)+"al$s=%q#{  "%######.              #########            "  ;;"%c"%126+$s<<
126}";d.gsub!(/  "##########.           #######%             "  |\s|".*"/,"");;
require"zlib"||  "###########           :######.             "  ;d=d.unpack"C*"
d.map{|c|n=(n||  ":#########:           .######: .           "  )*90+(c-2)%91};
e=["%x"%n].pack   " :#######%           :###### #:          "   &&"H*";e=Zlib::
Inflate.inflate(   "  ######%           .####% ::          "   &&e).unpack("b*"
)[0];22.times{|y|   "  ####%             %###             "   ;w=(Math.sqrt(1-(
(y*2.0-21)/22)**(;   " .###:             .#%             "   ;2))*23).floor;(w*
2-1).times{|x|u=(e+    " %##                           "    )[y*z=360,z]*2;u=u[
90*x/w+v+90,90/w];s[(    " #.                        "    ;y*80)+120-w+x]=(""<<
32<<".:%#")[4*u.count((     " .                   "     ;"0"))/u.size]}};;puts\
s+";_ The Qlobe#{" "*18+ (       "#  :#######"       ;"Copyright(C).Yusuke End\
oh, 2010")}";exit~;_ The Qlobe                  Copyright(C).Yusuke Endoh, 2010

After that, just run this script using:

while true; do clear; ruby a.rb | tee b.rb; sleep 0.2; mv -f b.rb a.rb; done

Ruby 2.0 lançado! O que há de novo?

ruby2

A versão 2.0 do Ruby foi lançada há dois dias.

Eu pensei em escrever um post listando e comentando cada uma das novas features, alterações, melhorias e incompatibilidades (quase nenhuma, felizmente) da linguagem. Mas acabei encontrando dois posts muito bons que fazem exatamente isso. O primeiro utilizando exemplos de códigos e o segundo são os slides do Urabe Shyouhe. Então, não deixe de ler:

http://blog.marc-andre.ca/2013/02/23/ruby-2-by-example/
https://speakerdeck.com/shyouhei/whats-new-in-ruby-2-dot-0

A simple way to deploy your Rails applications

Sometimes I prefer to use a simpler way to deploy my Rails applications instead to install and configure any tool (e.g.: capistrano).

A very simple way to do this is to create a shell script within the /script directory, that will access the server via SHH:

#! /bin/bash
# script/deploy.sh

TAG=deploy_$(date +"%F_%Hh%M")
git tag -m '' -a $TAG
git push --tags

ssh user@your_domain.com << 'SSH'
  cd /var/rails_apps/my_app
  rm -rf public/assets
  git pull
  bundle install --without development test
  bundle exec rake db:migrate db:seed assets:clean assets:precompile
  touch tmp/restart.txt
  git describe > public/version.txt
SSH

After that, a tag is created in the git repository. This way you know exactly the date and time the deployment was performed.

And you can find out which version (tag from git) is in production accessing the URL your_domain.com/version.txt.

your_domain

Update on March 8, 2013:

I created another script which accepts the -q param (quick).
https://gist.github.com/lucascaton/5118852

Transformando um Array em um Enumerator no Ruby

Existem alguns casos em que você precisa modificar um array (aumentá-lo por exemplo) repetindo os valores presentes no array original.

Uma forma bem interessante de fazer isso é convertendo tal array para um objeto Enumerator. Para isso, existe o método Enumerator#cycle. Imagine o seguinte array:

array = [1, 3, 5, 7]

Ao rodar o método cycle, veja o que acontece:

array.cycle
#=> #<Enumerator: [1, 3, 5, 7]:cycle>

Podemos agora usar o método Enumerator#take e modificar o array original como quisermos. Por exemplo, vamos dobrar o seu tamanho:

array.cycle.take(8)
#=> [1, 3, 5, 7, 1, 3, 5, 7]

Foi criado um array do tamanho especificado no parametro do método take.

Isso é útil – por exemplo – em casos similares à esse código da gem boleto_bancario. Em algoritmos de IA também é bastante comum precisar desse tipo de modificação em arrays.

Poltergeist

Replacing “Selenium” by “Poltergeist”

Poltergeist

Using the tip from my friend @pellegrino, I replaced “Selenium” by “Poltergeist” in a personal project. Poltergeist is a PhantomJS driver for Capybara.

Basically, this is what I did:

Include in the Gemfile:

gem 'poltergeist'

Update Capybara configuration:

Capybara.configure do |config|
  # config.javascript_driver = :selenium
  config.javascript_driver = :poltergeist
end

And run the specs!

If you are testing some confirm() javascript method and you have a code similar to page.driver.browser.switch_to.alert.accept, you’ll got this error:

undefined method `switch_to'

I tried to fix it and find out that Poltergeist always returns true for a call to window.confirm. There’s no way to make it return false (at the moment), but it should not prevent your test from running.

So, I just removed that line and it works!

Results:

Before:
Finished in 1 minute 35.45 seconds

After:
Finished in 41.03 seconds