Tag Archives: ruby

Como aprender Ruby e Rails

ruby_rails

Vários amigos tem me perguntado como podem aprender a programar em Ruby e Rails. Vou postar aqui os mesmos vídeos e dicas que mandei pra eles, caso alguém tenha interesse também:

An awesome Wiki built with Ruby and Rails!

I’ve been worked on a small (but awesome) open-source project.

I’m talking about ruby_wiki – a simple wiki built with Ruby on Rails:
https://github.com/lucascaton/ruby_wiki

As I said before – it’s quite simple, although it works fine.
Anyway, would be nice to have more features in this project, so, if you’re a developer and have any interest in that, feel free to fork the project and contribute.

Some screenshots:


1


2


3


4


5


6

Have a Rails 2 app? You can run it on the newest Ruby!

old_rails_with_new_ruby

Do you have a legacy Rails application which is still running on Rails 2?

There are several reasons to migrate your application to new Rails versions, like to improve the security, to be able to use a better syntax, to take advantage of new features and also because most of current gems will only work on Rails 3 or higher. However, sometimes it’s hard to do that, especially for big projects. And certainly today there’re many project still running on Rails 2.

But there’s one good thing you can (and should) do! I’m talking about to use the newest Ruby version. Yes, I’m serious. The current Ruby version is 2.1.1 – and it’s not so hard to get it working fine with Rails 2.

Obviously, would be better if you have a good test coverage.

That said, let’s do it in 12 steps:

Replacements

1. Gemfile

Rails 2 apps don’t use Bundler by default, so if you don’t have Bundler managing your gems yet, you should check here how to do that.

# There's no way to ensure that next Ruby versions will work,
# but so far the current one works fine:
ruby '2.1.1'

# The same for rake:
rake '10.1.1'

# Maybe you might need the iconv gem:
gem 'iconv'

2. Rakefile

# Replace:
# require 'rake/rdoctask'

# with:
require 'rake/task'

3. config.ru

# Replace:
# require 'config/environment'

# with:
require File.dirname(__FILE__) + '/config/environment'

4. FasterCSV => CSV

Replace all FasterCSV constant with CSV. Also, include require 'csv' to relevant files (or include this require to config/environment.rb).

Inclusions

5. config/environment.rb

# Include this before the `Rails::Initializer.run` line:
if RUBY_VERSION >= '2.0.0'
  module Gem
    def self.source_index
      sources
    end

    def self.cache
      sources
    end

    SourceIndex = Specification

    class SourceList
      # If you want vendor gems, this is where to start writing code.
      def search(*args); []; end
      def each(&block); end
      include Enumerable
    end
  end
end

6. config/initializers/paperclip.rb

# The patches below are needed when using an old version of PaperClip + Ruby 2.x
# https://github.com/thoughtbot/paperclip/issues/262
# https://github.com/thoughtbot/paperclip/commit/1bcfc14388d0651c5fc70ab9ca3511144c698903

module Paperclip
  class Tempfile < ::Tempfile
    def make_tmpname(basename, n)
      extension = File.extname(basename)
      sprintf('%s,%d,%d%s', File.basename(basename, extension), $$, n.to_i, extension)
    end
  end
end

module IOStream
  def to_tempfile
    name = respond_to?(:original_filename) ? original_filename : (respond_to?(:path) ? path : 'stream')
    tempfile = Tempfile.new(['stream', File.extname(name)])
    tempfile.binmode
    self.stream_to(tempfile)
  end
end

New files

7. config/initializers/ruby2.rb

# This is a very important monkey patch to make Rails 2.3.18 to work with Ruby 2.x
# If you're thinking to remove it, really, don't, unless you know what you're doing.
# KTHXBYE

if Rails::VERSION::MAJOR == 2 && RUBY_VERSION >= '2.0.0'
  module ActiveRecord
    module Associations
      class AssociationProxy
        def send(method, *args)
          if proxy_respond_to?(method, true)
            super
          else
            load_target
            @target.send(method, *args)
          end
        end
      end
    end
  end
end

RSpec

8. Make sure you’re using the last compatible version with Rails 2.3.18:

gem 'rspec', '1.3.2'
gem 'rspec-rails', '1.3.4'

9. Remove the file script/spec.

10. lib/tasks/rspec.rake

Remove all the following lines:

gem 'test-unit', '1.2.3' if RUBY_VERSION.to_f >= 1.9
rspec_gem_dir = nil

Dir["#{Rails.root}/vendor/gems/*"].each do |subdir|
  rspec_gem_dir = subdir if subdir.gsub("#{Rails.root}/vendor/gems/","") =~ /^(\w+-)?rspec-(\d+)/ && File.exist?("#{subdir}/lib/spec/rake/spectask.rb")
end

rspec_plugin_dir = File.expand_path(File.dirname(__FILE__) + '/../../vendor/plugins/rspec')

if rspec_gem_dir && (test ?d, rspec_plugin_dir)
  raise "\n#{'*'*50}\nYou have rspec installed in both vendor/gems and vendor/plugins\nPlease pick one and dispose of the other.\n#{'*'*50}\n\n"
end

if rspec_gem_dir
  $LOAD_PATH.unshift("#{rspec_gem_dir}/lib")
elsif File.exist?(rspec_plugin_dir)
  $LOAD_PATH.unshift("#{rspec_plugin_dir}/lib")
end

Ruby syntax

11. Some details has been changed in Ruby syntax, especially from 1.8.x to 1.9.x.

Example 1:

# Replace:
when 'foo': bar

# with:
when 'foo' then bar

Example 2:

The behaviour for protected methods in new Ruby versions is a little bit different. See more in this post.

# In some cases, you might need to replace:
respond_to?(:foobar)

# with:
respond_to?(:foobar, true)

Example 3 (Yaml files):

# Replace:
order: [ :day, :month, :year ]

# with:
order:
  - :year
  - :month
  - :day

Ruby changes

12. The default encoding for Ruby 2.0 (or higher) is UTF-8. So, remove all the code similar to:

# encoding: utf-8

Or:

$KCODE = 'UTF-8'

Conclusion

Each project could have different issues.
But I hope this little guide helps you to use new Ruby versions in legacy Rails applications!

Apresentação online sobre as novidades do Rails 4

Screen Shot 2013-07-02 at 10.22.18 PM

O Rails 4 acabou de ser lançado e tem várias novidades bacanas! Aprenda o que mudou, o que são Strong Parameters, turbolinks, etags, requests com streaming e outras coisas interessantes.

Hoje fiz uma apresentação online pela Eventials e pela Locaweb sobre as novidades do Rails 4. Quem quiser assistir, a palestra está gravada e disponível no link abaixo:

https://www.eventials.com/pt-br/locaweb/o-que-ha-de-novo-no-rails-4-com-lucas-caton/

Seguem os slides:


Contar a frequência de objetos em um array usando Ruby

Uma dica rápida: às vezes precisamos contabilizar qual a frequência de objetos em um array usando Ruby.

Por exemplo, um array %w(dog dog cat) tem dois elementos “dog” e um “cat”. Para transformar isso em um hash, podemos fazer:

words = %w(dog dog cat)

Hash[words.group_by{ |w| w }.map { |w, words| [w, words.size] }]

O retorno disso seria:

{
    "dog" => 2,
    "cat" => 1
}

[#IF] Screencasts de Ruby on Rails para iniciantes

ruby_rails

Pra quem não entendeu o que é a hashtag #IF, veja esse post do Fabio Akita.

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