Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Minicurso Ruby e Rails

15,540 views

Published on

Slides do minicurso de Ruby e Rails apresentado no Maré de Agilidade Swell Salvador e Fortaleza.

Published in: Technology
  • Hola, muy buen curso!
    Me gustaría bajarme la versión en pdf pero al intentarlo, genera un archivo con una extensión no reconocida 'rubyonrails-090328093416-phpapp01.key'
    Gracias!
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • BOM
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Need : 'Ruby on Rail Developer' at NJ
    Position : Ruby on Rail Developer

    Location : NJ

    Duration : 6+ Months



    Client is looking for “Ruby on Rail Developer” Experience with Ruby on Rail Developer, Heroku or Engine Factory, ect;

    Client is Looking more of an architect on such development methodology but he/she has to know how to code too.
    Any experience on Heroku or Engine Factory would be a plus.
    Kindly send your resume along with the following information……………………….Please,

    FULL NAME:

    Best contact number:

    Current Location:

    Visa Status (US Citizen/GC):

    Availability (specify the notice period, if so required):

    Expected Hourly / PERANNUM Rate (on W2 Please specify):

    Ready to relocate to NJ, if hired for this position (Yes/No):

    Ready to Face to Face Interview (Yes/No):

    Vijay Bhaskar



    Globalnest LLC

    281 state Route 79, Suite 208

    Morganville, NJ 07751



    Voice: (732)-333-4808

    Fax: (732) 333-5946

    Email: bhaskar@globalnest.com
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Need : 'Ruby on Rail Developer' at NJ
    Position : Ruby on Rail Developer

    Location : NJ

    Duration : 6+ Months



    Client is looking for “Ruby on Rail Developer” Experience with Ruby on Rail Developer, Heroku or Engine Factory, ect;

    Client is Looking more of an architect on such development methodology but he/she has to know how to code too.
    Any experience on Heroku or Engine Factory would be a plus.
    Kindly send your resume along with the following information……………………….Please,

    FULL NAME:

    Best contact number:

    Current Location:

    Visa Status (US Citizen/GC):

    Availability (specify the notice period, if so required):

    Expected Hourly / PERANNUM Rate (on W2 Please specify):

    Ready to relocate to NJ, if hired for this position (Yes/No):

    Ready to Face to Face Interview (Yes/No):
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
  • Excelente apresentação. Como posso fazer baixá-la?
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Minicurso Ruby e Rails

  1. 1. Mini Curso Ruby e Rails 1
  2. 2. 2
  3. 3. Objetivo 3
  4. 4. Agenda Ruby Rails JRuby JRubyOnRails GlassfishOnRails JBossOnRails 4
  5. 5. Ruby é... “Uma linguagem dinâmica, open source com foco na simplicidade e na produtividade.Tem uma sintaxe elegante de leitura natural e fácil escrita. http://www.ruby-lang.org/pt/ 5
  6. 6. Instalando Ruby (Ubuntu) $ sudo apt-get install ruby irb Lendo lista de pacotes... Pronto Construindo árvore de dependências Lendo estado da informação... Pronto Os pacotes extra a seguir serão instalados: irb1.8 libreadline-ruby1.8 libruby1.8 ruby1.8 Pacotes sugeridos: rdoc1.8 ri1.8 ruby1.8-examples Os NOVOS pacotes a seguir serão instalados: irb irb1.8 libreadline-ruby1.8 libruby1.8 ruby ruby1.8 0 pacotes atualizados, 6 pacotes novos instalados, (...) Instalando irb (4.1) ... Instalando ruby (4.1) ... Processing triggers for libc6 ... ldconfig deferred processing now taking $ 6
  7. 7. $ ruby -v ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux] $ irb -v irb 0.9.5(05/04/13) Testando a instalação 7
  8. 8. Linguagem de Script como python, perl e bash $ ls Code Library Sentilla iLiberty+ Payloads workspace Desktop Music Snapshots liferay Documents Pictures TryLock.txt pgadmin.log $ echo "viva a bahia" viva a bahia $ i=$(date) Em BASH, os comandos $ echo $i podem ser executados no interpretador (prompt) e o Sat Mar 21 15:19:37 BRT 2009 resultado obtido imediatametne... $ 8
  9. 9. Linguagem de Script .sh $ cat teste.sh ls ... ou os comandos podem ser todos executados de echo "viva a bahia" uma só vez (bash script) i=$(date) echo $i $ bash teste.sh Code Library Sentilla iLiberty+ Payloads teste.sh Desktop Music Snapshots liferay Documents Pictures TryLock.txt pgadmin.log viva a bahia Sat Mar 21 15:25:07 BRT 2009 9 $
  10. 10. Interpretador Ruby irb $ irb irb(main):001:0> puts "viva a bahia" viva a bahia => nil irb(main):002:0> a = 9 => 9 Assim como no BASH, os comandos Ruby podem ser irb(main):003:0> puts a executados no interpretador (Ruby) e o resultado obtido 9 imediatametne... => nil irb(main):004:0> Time.now => Sat Mar 21 15:33:49 -0300 2009 10
  11. 11. Interpretador Ruby .rb $ cat teste.rb puts "viva a bahia" a = 9 ... ou os comandos podem puts a ser todos executados de puts Time.now uma só vez (script ruby) $ ruby teste.rb viva a bahia 9 Sat Mar 21 15:40:17 -0300 2009 11
  12. 12. Ruby é OO 12
  13. 13. POO grafo de dependências 13
  14. 14. classes objetos mensagens 14
  15. 15. Urso ze_colmeia:Urso raça:String raça = Grizzly cor:String cor = marrom grunir() grunir() hibernar() hibernar() classe objeto 15
  16. 16. Ruby é OO *tudo* é objeto $ irb irb(main):001:0> 1.class => Fixnum irb(main):002:0> "bahia".class => String irb(main):003:0> Time.class => Class 16
  17. 17. objetos têm métodos (classes também podem ter) irb(main):006:0> 1.class => Fixnum irb(main):007:0> 1.methods => ["%", "odd?", "inspect", "prec_i", "<<", "tap", "div", "&", "clone", ">>", "public_methods", "object_id", "__send__", "instance_variable_defined?", "equal?", "freeze", "to_sym", "*", "ord", "+", "extend", "next", "send", "round", "methods", "prec_f", "-", "even?", "singleton_method_added", "divmod", "hash", "/", "integer?", "downto", "dup", "to_enum", "instance_variables", "|", "eql?", "size", "instance_eval", "truncate", "~", "id", "to_i", "singleton_methods", "modulo", "taint", "zero?", "times", "instance_variable_get", "frozen?", "enum_for", "display", "instance_of?", "^", "method", "to_a", "+@", "-@", "quo", "instance_exec", "type", "**", "upto", "to_f", "<", "step", "protected_methods", "<=>", "between?", "==", "remainder", ">", "===", "to_int", "nonzero?", "pred", "instance_variable_set", "coerce", "respond_to?", "kind_of?", "floor", "succ", ">=", "prec", "to_s", "<=", "fdiv", "class", "private_methods", "=~", "tainted?", "__id__", "abs", "untaint", "nil?", "chr", "id2name", "is_a?", "ceil", "[]"] 17
  18. 18. métodos retornam outros objetos irb(main):008:0> 1.methods.class => Array irb(main):010:0> 1.methods.methods => ["find", "[]=", "inspect", "tap", "<<", "reject!", "flatten", "&", "clone", "push", "rindex", "take", "__send__", "object_id", "public_methods", "reject", "transpose", "instance_variable_defined?", "minmax", "choice", "freeze", "equal?", "indexes", "member?", "each", "delete", "*", "sort", "extend", "partition", "map!", "uniq", "each_cons", "+", "send", "any?", "each_with_index", "to_ary", "methods", "values_at", "-", "detect", "pack", "hash", "dup", "take_while", "join", "pop", "replace", "instance_variables", "to_enum", "reverse", "collect", "clear", "permutation", "slice!", "min_by", "|", "sort_by", "eql?", "indices", "size", "group_by", "enum_cons", "id", "instance_eval", "at", "one?", "enum_with_index", "flatten!", "singleton_methods", "find_index", "delete_at", "nitems", "taint", "empty?", "shift", "drop", "instance_variable_get", "enum_for", "map", "frozen?", "fill", "display", "instance_of?", "max_by", "uniq!", "combination", "method", "grep", "to_a", "first", "compact", "instance_exec", "type", "fetch", "none?", "reverse_each", "protected_methods", "find_all", "<=>", "delete_if", "==", "min", "reverse!", "insert", "===", "unshift", "drop_while", "instance_variable_set", "sort!", "assoc", "concat", "each_slice", "inject", "respond_to?", "kind_of?", "minmax_by", "product", "count", "to_s", "class", "shuffle!", "last", "index", "zip", "private_methods", "=~", "tainted?", "__id__", "select", "length", "max", "shuffle", "untaint", "nil?", "entries", "each_index", "cycle", "slice", "reduce", "collect!", "rassoc", "enum_slice", "include?", "is_a?", "[]", "all?", "compact!"] 18
  19. 19. objetos trocam mensagens entre si irb(main):011:0> 1 .methods.sort => ["%", "&", "*", "**", "+", "+@", "-", "-@", "/", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", ">>", "[]", "^", "__id__", "__send__", "abs", "between?", "ceil", "chr", "class", "clone", "coerce", "display", "div", "divmod", "downto", "dup", "enum_for", "eql?", "equal?", "even?", "extend", "fdiv", "floor", "freeze", "frozen?", "hash", "id", "id2name", "inspect", "instance_eval", "instance_exec", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "integer?", "is_a?", "kind_of?", "method", "methods", "modulo", "next", "nil?", "nonzero?", "object_id", "odd?", "ord", "prec", "prec_f", "prec_i", "pred", "private_methods", "protected_methods", "public_methods", "quo", "remainder", "respond_to?", "round", "send", "singleton_method_added", "singleton_methods", "size", "step", "succ", "taint", "tainted?", "tap", "times", "to_a", "to_enum", "to_f", "to_i", "to_int", "to_s", "to_sym", "truncate", "type", "untaint", "upto", "zero?", "|", "~"] 19
  20. 20. então, tudo é objeto e troca de mensagem entre eles irb(main):034:0> 1+2 => 3 irb(main):035:0> 3*5 => 15 repare que +, -, *, / ... são métodos do objeto da classe Fixnum 20
  21. 21. classes também podem ter métodos irb(main):031:0> 1.class => Fixnum irb(main):032:0> 1.class.methods.sort => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=", "__id__", "__send__", "allocate", "ancestors", "autoload", "autoload?", "class", "class_eval", "class_exec", "class_variable_defined?", "class_variables", "clone", "const_defined?", "const_get", "const_missing", "const_set", "constants", "display", "dup", "enum_for", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "include?", "included_modules", "induced_from", "inspect", "instance_eval", "instance_exec", "instance_method", "instance_methods", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "method_defined?", "methods", "module_eval", "module_exec", "name", "nil?", "object_id", "private_class_method", "private_instance_methods", "private_method_defined?", "private_methods", "protected_instance_methods", "protected_method_defined?", "protected_methods", "public_class_method", "public_instance_methods", "public_method_defined?", "public_methods", "respond_to?", "send", "singleton_methods", "superclass", "taint", "tainted?", "tap", "to_a", "to_enum", "to_s", "type", "untaint"] 21
  22. 22. De onde vem isso? .class, .methods ? 22
  23. 23. Object 1 é Fixnum, que extende Integer, Numeric que extende Numeric, que extende Object. Integer irb(main):026:0> 1.class => Fixnum irb(main):027:0> 1.class.superclass Fixnum => Integer irb(main):028:0> 1.class.superclass.superclass => Numeric irb(main):029:0> 1.class.superclass.superclass.superclass => Object irb(main):030:0> 1.class.superclass.superclass.superclass.superclass => nil 23
  24. 24. Toda classe Ruby extende de Object Object ... Array Fixnum ... 24
  25. 25. todos os métodos da classe Object estão disponíveis em qualquer objeto Ruby irb(main):033:0> Object.methods.sort => ["<", "<=", "<=>", "==", "===", "=~", ">", ">=", "__id__", "__send__", "allocate", "ancestors", "autoload", "autoload?", "class", "class_eval", "class_exec", "class_variable_defined?", "class_variables", "clone", "const_defined?", "const_get", "const_missing", "const_set", "constants", "display", "dup", "enum_for", "eql?", "equal?", "extend", "freeze", "frozen?", "hash", "id", "include?", "included_modules", "inspect", "instance_eval", "instance_exec", "instance_method", "instance_methods", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "is_a?", "kind_of?", "method", "method_defined?", "methods", "module_eval", "module_exec", "name", "new", "nil?", "object_id", "private_class_method", "private_instance_methods", "private_method_defined?", "private_methods", "protected_instance_methods", "protected_method_defined?", "protected_methods", "public_class_method", "public_instance_methods", "public_method_defined?", "public_methods", "respond_to?", "send", "singleton_methods", "superclass", "taint", "tainted?", "tap", "to_a", "to_enum", "to_s", "type", "untaint"] 25
  26. 26. http://www.ruby-doc.org/ 26
  27. 27. @variable def while until Sintaxe Ruby for end class do < attr_accessor 27
  28. 28. Métodos def soma a, b a+b end puts soma 3, 4 28
  29. 29. Classe numero.rb class Numero # atributos # metodos end 29
  30. 30. Classe construtor class Numero def initialize v @valor = v end end irb(main):001:0> require 'numero' => true irb(main):002:0> n = Numero.new 1 => #<Numero:0x54ec0 @v=1> 30
  31. 31. Classe accessors class Numero def initialize v @valor = v end end irb(main):001:0> require 'numero' => true irb(main):002:0> n = Numero.new 1 => #<Numero:0x54e98 @valor=1> irb(main):003:0> n.valor NoMethodError: undefined method `valor' for #<Numero:0x54e98 @valor=1> from (irb):3 31
  32. 32. Classe accessors class Numero def initialize v @valor = v end attr_accessor :valor end irb(main):002:0> require 'numero' => true irb(main):003:0> n = Numero.new 1 => #<Numero:0x500a0 @valor=1> irb(main):004:0> n.valor => 1 32
  33. 33. Classe herança funcionario.rb pessoa.rb class Pessoa class Funcionario < Pessoa def initialize nome def initialize n, m @nome = nome super n end @matricula = m end attr_accessor :nome attr_accessor :matricula end end require 'pessoa' require 'funcionario' p = Pessoa.new 'Alexandre' puts "A pessoa #{p.nome} foi criada" f = Funcionario.new 'Ze', '1234' puts "O funcionario #{f.nome} de matricula #{f.matricula} foi criado" 33
  34. 34. Variáveis definição irb(main):001:0> a=1 => 1 irb(main):002:0> a = 1 => 1 irb(main):003:0> puts a 1 => nil irb(main):004:0> a.class => Fixnum irb(main):005:0> a = "Agilidade" => "Agilidade" irb(main):006:0> a.class => String irb(main):007:0> puts a Agilidade => nil 34
  35. 35. Variáveis escopo x variável local @x variável de instância @@x variável de classe $x variável global 35
  36. 36. Números irb(main):010:0> a = 1 => 1 irb(main):011:0> a.class => Fixnum irb(main):012:0> a = 1.0 => 1.0 irb(main):013:0> a.class => Float irb(main):014:0> a = 11111111111111111111111111111111 => 11111111111111111111111111111111 irb(main):015:0> a.class => Bignum 36
  37. 37. Booleans Possíveis valores if a a = true verdadeiro a = false falso a = “qqcoisa” verdadeiro a = nil falso a=0 verdadeiro a=1 verdadeiro 37
  38. 38. Strings “ ” vs ‘ ’ irb(main):001:0> a = "capoeira" => "capoeira" irb(main):002:0> a.class => String irb(main):003:0> a = 'capoeira' => "capoeira" irb(main):004:0> a.class => String irb(main):005:0> a = 'capoeiranbrasil' => "capoeiranbrasil" irb(main):006:0> puts a capoeiranbrasil => nil irb(main):007:0> a = "capoeiranbrasil" => "capoeiranbrasil" irb(main):008:0> puts a capoeira brasil => nil 38
  39. 39. Strings expansão de variáveis irb(main):009:0> b = "o valor de 'a' eh #{a}" => "o valor de 'a' eh capoeiranbrasil" 39
  40. 40. Strings múltiplas linhas irb(main):010:0> a = <<FIM irb(main):011:0" aqui comeca irb(main):012:0" um texto irb(main):013:0" multilinha irb(main):014:0" que so vai ter fim irb(main):015:0" quando eu escrever FIM irb(main):016:0" no inicio da linha irb(main):017:0" FIM => "aqui comecanum textonmultilinhanque so vai ter fim nquando eu escrever FIMnno inicio da linhan" irb(main):018:0> puts a aqui comeca um texto multilinha que so vai ter fim quando eu escrever FIM no inicio da linha => nil 40
  41. 41. CONSTANTES irb(main):019:0> CONSTANTE = "rubyonrails" => "rubyonrails" irb(main):020:0> CONSTANTE = "javaonrails" (irb):20: warning: already initialized constant CONSTANTE => "javaonrails" 41
  42. 42. Arrays irb(main):022:0> a = ['arroz', 'feijao', 'abobora'] => ["arroz", "feijao", "abobora"] irb(main):023:0> puts a arroz feijao abobora => nil irb(main):024:0> a.class => Array irb(main):025:0> a[0] => "arroz" irb(main):026:0> a[1] => "feijao" irb(main):027:0> a[2] => "abobora" irb(main):028:0> a[3] => nil 42
  43. 43. Arrays irb(main):029:0> a = Array.new => [] irb(main):030:0> a.length => 0 irb(main):031:0> a[1] = "couve" => "couve" irb(main):032:0> a[0] = "pe-de-porco" => "pe-de-porco" irb(main):033:0> puts a pe-de-porco couve => nil irb(main):034:0> a[2] = "mandioca" => "mandioca" irb(main):035:0> a => ["pe-de-porco", "couve", "mandioca"] 43
  44. 44. Arrays irb(main):038:0> puts a pe-de-porco couve mandioca => nil irb(main):039:0> puts a[0] pe-de-porco => nil irb(main):041:0> a.methods.sort => ["&", "*", "+", "-", "<<", "<=>", "==", "===", "=~", "[]", "[]=", "__id__", "__send__", "all?", "any?", "assoc", "at", "choice", "class", "clear", "clone", "collect", "collect!", "combination", "compact", "compact!", "concat", "count", "cycle", "delete", "delete_at", "delete_if", "detect", "display", "drop", "drop_while", "dup", "each", "each_cons", "each_index", "each_slice", "each_with_index", "empty?" (...) 44
  45. 45. Hash chave=valor irb(main):001:0> a = { 1 => "alexandre", 2 => "luciana" } => {1=>"alexandre", 2=>"luciana"} irb(main):002:0> a.class => Hash irb(main):003:0> a = { 1 => "alexandre", "b3" => 802148 } => {1=>"alexandre", "b3"=>802148} irb(main):004:0> a.class => Hash irb(main):005:0> a = Hash.new => {} irb(main):006:0> a[1] = "cavalo" => "cavalo" irb(main):007:0> a[2] = "leao" => "leao" irb(main):008:0> a.class => Hash 45
  46. 46. Blocos irb(main):001:0> a = [ "xp", "scrum", "lean" ] => ["xp", "scrum", "lean"] irb(main):002:0> a.each do |metodo| irb(main):003:1* puts metodo irb(main):004:1> end xp scrum lean => ["xp", "scrum", "lean"] 46
  47. 47. Closure irb(main):014:0> a = %w(huguinho zezinho luizinho) => ["huguinho", "zezinho", "luizinho"] irb(main):015:0> x = 1 => 1 irb(main):016:0> a.each_with_index do |elemento, indice| irb(main):017:1* puts "x=#{x} e indice=#{indice}" irb(main):018:1> x = x + indice irb(main):019:1> end x=1 e indice=0 x=1 e indice=1 x=2 e indice=2 => ["huguinho", "zezinho", "luizinho"] irb(main):020:0> x => 4 47
  48. 48. if puts "Digite um numero: " STDOUT.flush a = gets.chomp.to_i if a == 1 puts "voce digitou 'um'" elsif a == 2 puts "voce digitou 'dois'" else puts "voce digitou um valor desconhecido" end 48
  49. 49. case puts "Digite um numero: " STDOUT.flush a = gets.chomp.to_i case a when 1 puts "voce digitou 'um'" when 2 puts "voce digitou 'dois'" when 3..9 puts "voce digitou algo entre tres e nove" else puts "voce digitou um valor desconhecido" end 49
  50. 50. while cmd = "" while ! cmd.eql? "sair" puts "Digite um comando: " STDOUT.flush cmd = gets.chomp end puts "Voce saiu." 50
  51. 51. for for i in 1..10 puts i end 51
  52. 52. labs 1. Imprimir números de 1 a 20 2. Impirimir números ímpares de 1 a 20 3. Imprimir, em ordem invesa, números ímpares de 1 a 20 4. Calcular idade a partir da data de nascimento 52
  53. 53. Quer saber mais? • http://www.ruby-doc.org • http://www.ruby-lang.org/pt • http://www.rubyonbr.org • http://peepcode.com • http://www.rubylearning.com • http://www.rubyquiz.com • http://why.nomedojogo.com 53
  54. 54. Rails http://rubyonrails.org 54
  55. 55. Rails http://www.rubyonrails.pro.br 55
  56. 56. 56
  57. 57. Instalando RubyGems $ sudo apt-get install rubygems Lendo lista de pacotes... Pronto Construindo árvore de dependências Lendo estado da informação... Pronto Os pacotes extra a seguir serão instalados: libgems-ruby1.8 libopenssl-ruby1.8 rdoc1.8 (...) Descompactando rubygems (de .../rubygems_0.9.4-4_all.deb) ... Instalando rdoc1.8 (1.8.6.111-2ubuntu1.2) ... Instalando libopenssl-ruby1.8 (1.8.6.111-2ubuntu1.2) ... Instalando libgems-ruby1.8 (0.9.4-4) ... Instalando rubygems (0.9.4-4) ... $ http://gems.rubyforge.org 57
  58. 58. $ sudo gem update --system Updating RubyGems... Attempting remote update of rubygems-update Successfully installed rubygems-update-1.3.1 Updating version of RubyGems to 1.3.1 Installing RubyGems 1.3.1 (...) RubyGems installed the following executables: /usr/bin/gem1.8 If `gem` was installed by a previous RubyGems installation, you may need to remove it by hand. RubyGems system software updated $ Certifique-se de que a última versão do RubyGem foi instalada 58
  59. 59. $ sudo apt-get install sqlite3 Lendo lista de pacotes... Pronto Construindo árvore de dependências Lendo estado da informação... Pronto (..) Baixados 19,9kB em 0s (23,6kB/s) Selecionando pacote previamente não selecionado sqlite3. (Lendo banco de dados ... 167352 arquivos e diretórios atualmente instalados.) Descompactando sqlite3 (de .../sqlite3_3.4.2-2_i386.deb) ... Instalando sqlite3 (3.4.2-2) ... Instalando banco de dados sqlite 59
  60. 60. $ sudo apt-get install build-essential ruby1.8-dev libsqlite3-dev Lendo lista de pacotes... Pronto Construindo árvore de dependências Lendo estado da informação... Pronto (...) Descompactando build-essential (de .../build-essential_11.3ubuntu1_i386.deb) ... Selecionando pacote previamente não selecionado libsqlite3-dev. Descompactando libsqlite3-dev (de .../libsqlite3-dev_3.4.2-2_i386.deb) ... Selecionando pacote previamente não selecionado ruby1.8-dev. Descompactando ruby1.8-dev (de .../ruby1.8-dev_1.8.6.111-2ubuntu1.2_i386.deb) ... Instalando build-essential (11.3ubuntu1) ... Instalando libsqlite3-dev (3.4.2-2) ... Instalando ruby1.8-dev (1.8.6.111-2ubuntu1.2) ... Instalando dependências necessárias para o acesso ao banco via Ruby 60
  61. 61. $ sudo gem install sqlite3-ruby Building native extensions. This could take a while... Successfully installed sqlite3-ruby-1.2.4 1 gem installed Installing ri documentation for sqlite3-ruby-1.2.4... Installing RDoc documentation for sqlite3-ruby-1.2.4... Biblioteca do Ruby para acesso ao banco de dados sqlite 61
  62. 62. $ sudo gem install rails --version=2.2.2 Successfully installed activesupport-2.2.2 Successfully installed activerecord-2.2.2 Successfully installed actionpack-2.2.2 Successfully installed actionmailer-2.2.2 Successfully installed activeresource-2.2.2 Successfully installed rails-2.2.2 6 gems installed Installing ri documentation for activesupport-2.2.2... Installing ri documentation for activerecord-2.2.2... Installing ri documentation for actionpack-2.2.2... Installing ri documentation for actionmailer-2.2.2... Installing ri documentation for activeresource-2.2.2... Updating ri class cache with 2176 classes... Installing RDoc documentation for activesupport-2.2.2... Installing RDoc documentation for activerecord-2.2.2... Installing RDoc documentation for actionpack-2.2.2... Installing RDoc documentation for actionmailer-2.2.2... wInstalling RDoc documentation for activeresource-2.2.2... Instalando Rails 62
  63. 63. Caso o diretório de binários do RubyGem não tiver sido acrescentado ao PATH durante a instalação, faça-o manualmente. $ rails -v O programa 'rails' não está instalado atualmente. Você pode instalá- lo digitando: sudo apt-get install rails -bash: rails: comando não encontrado $ $ $ echo "export PATH=/var/lib/gems/1.8/bin:$PATH" >> ~/.bash_profile $ . ~/.bash_profile $ $ rails -v Rails 2.2.2 Verificando instalação do Rails 63
  64. 64. $ rails inscricao_evento create create app/controllers create app/helpers create app/models create app/views/layouts create config/environments create config/initializers create config/locales create db create doc Text create lib (...) create public/javascripts/dragdrop.js create public/javascripts/controls.js create public/javascripts/application.js create doc/README_FOR_APP create log/server.log create log/production.log create log/development.log create log/test.log Criando app Rails 64
  65. 65. inscricao_evento $ script/server => Booting WEBrick... => Rails 2.2.2 application started on http://0.0.0.0:3000 => Ctrl-C to shutdown server; call with --help for options [2009-03-22 15:46:11] INFO WEBrick 1.3.1 [2009-03-22 15:46:11] INFO ruby 1.8.7 (2008-08-11) [powerpc-darwin8] [2009-03-22 15:46:11] INFO WEBrick::HTTPServer#start: pid=2655 port=3000 Para testar a app, inicialize o servidor do Rails e acesse pelo browser... 65
  66. 66. Rails é MVC 66
  67. 67. MVC View Controller Model 67
  68. 68. MVC 68
  69. 69. MVC 69
  70. 70. Rails é MVC 70
  71. 71. Conceitos do Rails Scaffold Routes Model Tasks Controller Tests View Scripts Helpers Migration 71
  72. 72. Scaffold C.R.U.D 72
  73. 73. Scaffold Scaffolding is a meta-programming method of building database-backed software applications. It is a technique supported by some model-view-controller frameworks, in which the programmer may write a specification that describes how the application database may be used.The compiler uses this specification to generate code that the application can use to create, read, update and delete database entries, effectively treating the template as a "scaffold" on which to build a more powerful application. http://en.wikipedia.org/wiki/Scaffold_(programming) 73
  74. 74. Cria cadastro básico (CRUD) para entidade ‘participante’ $ script/generate scaffold participante email:string nome:string exists app/models/ exists app/controllers/ exists app/helpers/ create app/views/participantes exists app/views/layouts/ exists test/functional/ (...) dependency model exists app/models/ exists test/unit/ exists test/fixtures/ create app/models/participante.rb create test/unit/participante_test.rb create test/fixtures/participantes.yml create db/migrate create db/migrate/20090318135212_create_participantes.rb 74
  75. 75. Scaffold estrutura de diretórios 75
  76. 76. $ rake db:create:all (in /home/sea/alegomes/sea/mkt/inscricao_evento) $ rake db:migrate (in /home/sea/alegomes/sea/mkt/inscricao_evento) == CreateParticipantes: migrating ============================================ -- create_table(:participantes) -> 0.0045s == CreateParticipantes: migrated (0.0050s) =================================== $ Cria estrutura do banco de dados 76
  77. 77. Cadastro de participantes pronto 77
  78. 78. Por debaixo dos panos... 78
  79. 79. Model app/models 79
  80. 80. Controller app/controllers O nome do Controller é usado para acessá-lo 80
  81. 81. Controller app/controllers 81
  82. 82. Controller app/controllers teste_controller.rb 82
  83. 83. View app/views index.html.erb 83
  84. 84. Helper app/helpers teste_helper.rb 84
  85. 85. Routes config/routes.rb HTTP Request Controller.action GET /participantes/alegomes ParticipantesController.show http://guides.rubyonrails.org/routing.html 85
  86. 86. Routes config/routes.rb 86
  87. 87. Routes config/routes.rb Verbo HTTP URL Controller Action Descrição GET /participantes Participantes index Lista todos os participantes Apresenta formulario para GET /participantes/new Participantes new novo cadastro POST /participantes Participantes create Cria um novo participante Apresenta um participante GET /participantes/1 Participantes show específico Apresenta formulário para edição GET /participantes/1/edit Participantes edit dos dados de um participante Atualiza os dados de um PUT /participantes/1 Participantes update participante Apaga o registro de um DELETE /participantes/1 Participantes destroy participante 87
  88. 88. http://betterexplained.com/articles/intermediate-rails-understanding-models-views-and-controllers/ 88
  89. 89. Tasks rake rake -T 89
  90. 90. Scripts app/script • about • dbconsole • generate • plugin • runner • console • destroy • performance • process • server 90
  91. 91. Tests http://guides.rubyonrails.org/testing.html 91
  92. 92. Tests tipos Unitários Funcionais Integração 92
  93. 93. Tests conceitos Fixtures Suites Assertions 93
  94. 94. Tests fixtures test/fixtures/participantes.yml 94
  95. 95. Tests unit test/unit/participante_test.rb 95
  96. 96. Tests unit rake test:units 96
  97. 97. Tests functional test/functional/participantes_controller_test.rb 97
  98. 98. Tests functional rake test:functionals 98
  99. 99. Tests integration rake test:integration test/integration/* 99
  100. 100. Migration 1.0 1.1 1.2 100
  101. 101. Migrations Código para evolução do banco Código para retrocesso do banco 101
  102. 102. Migrations rake db:migrate 102
  103. 103. Revisão Migration Helpers Model Routes Controller Tasks View Tests Scaffold 103
  104. 104. labs Criar aplicação Rails Explorar os arquivos gerados Criar Scaffold para alguma entidade Criar testes unitários Criar testes funcionais 104
  105. 105. Quer saber mais? • http://guides.rubyonrails.org • http://api.rubyonrails.org 105
  106. 106. JRuby “ JRuby is an 100% pure-Java implementation of the Ruby programming language. http://jruby.codehaus.org 106
  107. 107. JRuby “ O JRuby é a implementação 100% em puro Java da linguagem de programação Ruby. Ou seja, permite que você rode seus scripts Ruby na máquina virtual Java http://ruby-br.org/?p=179 107
  108. 108. Forma mais fácil de instalação $ sudo apt-get install jruby Lendo lista de pacotes... Pronto Construindo árvore de dependências Lendo estado da informação... Pronto (...) Baixados 3483kB em 10s (334kB/s) Selecionando pacote previamente não selecionado jruby1.0. (Lendo banco de dados ... 167406 arquivos e diretórios atualmente instalados.) Descompactando jruby1.0 (de .../jruby1.0_1.0.2-2_all.deb) ... Instalando jruby1.0 (1.0.2-2) ... $ jruby1.0 -v ruby 1.8.5 (2008-01-07 rev 4810) [i386-jruby1.0.2] Instalação e teste do JRuby http://wiki.jruby.org/wiki/Getting_Started#QuickStart_with_JRuby 108
  109. 109. $ apt-cache search jruby jruby0.9 - 100% pure-Java implementation of Ruby jruby1.0 - 100% pure-Java implementation of Ruby A última versão dos repositórios do Ubuntu é jruby1.0 (obsoleta) 109
  110. 110. $ wget -c http://dist.codehaus.org/jruby/1.1.6/jruby-bin-1.1.6.zip $ unzip jruby-bin-1.1.6.zip $ sudo mv jruby-1.1.6/ /opt $ echo "export PATH=/opt/jruby-1.1.6/bin:$PATH" >> ~/.bash_profile $ . ~/.bash_profile $ jruby -v jruby 1.1.6 (ruby 1.8.6 patchlevel 114) (2008-12-17 rev 8388) [i386-java] Última versão instalada (jruby1.1.6) o/ http://wiki.jruby.org/wiki/Getting_Started#Installing_JRuby 110
  111. 111. $ jruby -S gem list *** LOCAL GEMS *** rake (0.8.3) rspec (1.1.11) sources (0.0.1) Teoricamente, tudo o que podia ser executado com ruby padrão (MRI)pode ser executado também com o jruby... 111
  112. 112. ...inclusive, uma app Rails! inscricao_evento$ jruby script/server => Booting WEBrick => Rails 2.3.2 application starting on http://0.0.0.0:3000 JRuby limited openssl loaded. gem install jruby-openssl for full support. http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL /opt/jruby-1.1.6/lib/ruby/gems/1.8/gems/actionpack-2.3.2/lib/ action_controller/middleware_stack.rb:84 warning: given block not used => Call with -d to detach => Ctrl-C to shutdown server [2009-03-19 10:19:21] INFO WEBrick 1.3.1 [2009-03-19 10:19:21] INFO ruby 1.8.6 (2008-12-17) [java] [2009-03-19 10:19:21] INFO WEBrick::HTTPServer#start: pid=8699 port=3000 112
  113. 113. JRubyOnRails Rails sendo executado sobre ambiente JRuby. 113
  114. 114. jruby não encontrou a gem ‘sqlite3’ do banco [2009-03-21 07:18:36] INFO WEBrick 1.3.1 [2009-03-21 07:18:36] INFO ruby 1.8.6 (2009-03-13) [java] [2009-03-21 07:18:36] INFO WEBrick::HTTPServer#start: pid=1010 port=3000 /! FAILSAFE /! Sat Mar 21 07:21:05 -0300 2009 Status: 500 Internal Server Error no such file to load -- sqlite3 114
  115. 115. $ jruby -S gem list *** LOCAL GEMS *** actionmailer (2.3.2, 2.2.2) actionpack (2.3.2, 2.2.2) activerecord (2.3.2, 2.2.2) activerecord-jdbc-adapter (0.9.1) activerecord-jdbcsqlite3-adapter (0.9.1) activeresource (2.3.2, 2.2.2) activesupport (2.3.2, 2.2.2) jdbc-sqlite3 (3.6.3.054) rails (2.3.2, 2.2.2) rake (0.8.3) rspec (1.1.11) sources (0.0.1) Realmente, a gem do sqlite não é listada 115
  116. 116. ! atenção às gems 116
  117. 117. $ jruby -S gem list $ gem list $ sudo gem list $ sudo jruby -S gem list *** LOCAL GEMS *** *** LOCAL GEMS *** *** LOCAL GEMS *** *** LOCAL GEMS *** actionmailer (2.3.2) actionmailer (2.2.2) actionmailer (2.2.2) actionmailer (2.3.2) actionpack (2.3.2) actionpack (2.2.2) actionpack (2.2.2) actionpack (2.3.2) activerecord (2.3.2) activerecord (2.2.2) activerecord (2.2.2) activerecord (2.3.2) activeresource (2.3.2) activeresource (2.2.2) activeresource (2.2.2) activeresource (2.3.2) activesupport (2.3.2) activesupport (2.2.2) activesupport (2.2.2) activesupport (2.3.2) rails (2.3.2) couchrest (0.12.4) couchrest (0.12.4) rails (2.3.2) rake (0.8.3) extlib (0.9.10) extlib (0.9.10) rake (0.8.3) rspec (1.1.11) json (1.1.3) json (1.1.3) rspec (1.1.11) sources (0.0.1) mime-types (1.16) mime-types (1.16) sources (0.0.1) mysql (2.7) mysql (2.7) rails (2.2.2) rails (2.2.2) rake (0.8.3) rake (0.8.3) rest-client (0.9) rest-client (0.9) rspec (1.2.0) rspec (1.2.0) rubygems-update (1.3.1) rubygems-update (1.3.1) sqlite3-ruby (1.2.4) sqlite3-ruby (1.2.4) No Mac, as gems do jruby são diferentes das gems do ruby 117
  118. 118. $ jruby -S gem list $ gem list $ sudo gem list $ sudo jruby -S gem list *** LOCAL GEMS *** *** LOCAL GEMS *** *** LOCAL GEMS *** *** LOCAL GEMS *** actionmailer (2.3.2) actionmailer (2.3.2) actionmailer (2.3.2) actionmailer (2.3.2) actionpack (2.3.2) actionpack (2.3.2) actionpack (2.3.2) actionpack (2.3.2) activerecord (2.3.2) activerecord (2.3.2) activerecord (2.3.2) activerecord (2.3.2) activeresource (2.3.2) activeresource (2.3.2) activeresource (2.3.2) activeresource (2.3.2) activesupport (2.3.2) activesupport (2.3.2) activesupport (2.3.2) activesupport (2.3.2) rails (2.3.2) rails (2.3.2) rails (2.3.2) rails (2.3.2) rake (0.8.3) rake (0.8.3) rake (0.8.4) rake (0.8.3) rspec (1.1.11) rspec (1.1.11) sqlite3-ruby (1.2.4) rspec (1.1.11) sources (0.0.1) sources (0.0.1) sources (0.0.1) No Linux, apenas o ‘sudo’ do ruby varia as gems 118
  119. 119. Caso o ambiente jruby não esteja com todos os pacotes instalados, instale-os $ jruby gem install sqlite3-ruby 119
  120. 120. Tentar instalar o sqlite3 no jruby pode dar problemas $ jruby gem install sqlite3-ruby JRuby limited openssl loaded. gem install jruby-openssl for full support. http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL Building native extensions. This could take a while... /opt/jruby-1.1.6/lib/ruby/1.8/mkmf.rb:7: JRuby does not support native extensions. Check wiki.jruby.org for alternatives. (NotImplementedError) from /opt/jruby-1.1.6/lib/ruby/1.8/mkmf.rb:1:in `require' from extconf.rb:1 ERROR: Error installing sqlite3-ruby: ERROR: Failed to build gem native extension. /opt/jruby-1.1.6/bin/jruby extconf.rb install sqlite3-ruby 120
  121. 121. Adaptador Java para o SQlite $ gem install activerecord-jdbcsqlite3-adapter JRuby limited openssl loaded. gem install jruby-openssl for full support. http://wiki.jruby.org/wiki/JRuby_Builtin_OpenSSL Successfully installed activerecord-jdbc-adapter-0.9.1 Successfully installed jdbc-sqlite3-3.6.3.054 Successfully installed activerecord-jdbcsqlite3-adapter-0.9.1 3 gems installed Installing ri documentation for activerecord-jdbc-adapter-0.9.1... Installing ri documentation for jdbc-sqlite3-3.6.3.054... Installing ri documentation for activerecord-jdbcsqlite3-adapter-0.9.1... Installing RDoc documentation for activerecord-jdbc-adapter-0.9.1... Installing RDoc documentation for jdbc-sqlite3-3.6.3.054... Installing RDoc documentation for activerecord-jdbcsqlite3-adapter-0.9.1... 121
  122. 122. inscricao_evento$ touch db/development.sqlite3 inscricao_evento$ vi config/database.yml development: adapter: sqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 development: adapter: jdbcsqlite3 database: db/development.sqlite3 pool: 5 timeout: 5000 122
  123. 123. o/ 123
  124. 124. labs 124
  125. 125. Deploy de aplicações Rails #railsescala? 125
  126. 126. Rails em Produção • CGI • FastCGI • Mongrel • mod_rails (Phusion Passenger) • JRuby 126
  127. 127. warbler 127
  128. 128. 128
  129. 129. GlassfishOnRails “ GlassFish v2 and v3 support JRuby on Rails. The JRuby Wiki captures the latest info on JRuby on Rails support on GlassFish. https://glassfish-scripting.dev.java.net/discover/ 129
  130. 130. GlassfishOnRails A forma mais fácil de se criar uma app Rails para o Glassfish é através da IDE Netbeans. 130
  131. 131. 131
  132. 132. 132
  133. 133. 133
  134. 134. 134
  135. 135. 135
  136. 136. 136
  137. 137. Suporte a WAR... ...Warble requerido 137
  138. 138. Sem suporte a WAR... ...Warble opcional. 138
  139. 139. Cliue em ‘Finish’ e aguarde a criação do projeto 139
  140. 140. 140
  141. 141. Execute a aplicação 141
  142. 142. 142
  143. 143. Aproveitando... 143
  144. 144. Nome do model e seus atributos 144
  145. 145. 145
  146. 146. 146
  147. 147. 147
  148. 148. Para saber mais... http://www.netbeans.org/download/flash/jruby_on_rails/jruby_on_rails.html 148
  149. 149. JBossOnRails “ Thesis: Rails can run well on JBoss Ruby-on-Rails can run well on JBoss AS. Through the magic of the JRuby team and Nick Sieger's JRuby-Rack, running a vanilla Rails app in a servlet container works. http://oddthesis.org/theses/jboss-rails 149
  150. 150. 150
  151. 151. jboss.org 151
  152. 152. 152
  153. 153. 153
  154. 154. Instead of building a Ruby Application Platform from the ground-up, TorqueBox leverages the existing ninja- grade functionality JBoss has been shipping for years in the JBoss Application Server. 154
  155. 155. 155
  156. 156. http://torquebox.org/documentation/browse/1.0.0.Beta13/installation.html 156
  157. 157. http://torquebox.org/documentation/browse/1.0.0.Beta13/rails-support.html 157
  158. 158. Saiba mais! http://torquebox.org 158
  159. 159. Lab? 159
  160. 160. Últimas palavras... O mercado esta mudando, e ser monolinguístico não é mais vantagem... 160
  161. 161. Últimas palavras... Ruby é uma linguagem poderosa, elegante e divertida de se trabalhar. 161
  162. 162. Últimas palavras... Rails conseguiu responder à clemência por produtividade vinda da comunidade Java, com estilo e personalidade. 162
  163. 163. Últimas palavras... Ruby e Rails são tecnologias amicíssimas da escola ágil de desenvolvimento. 163
  164. 164. Últimas palavras... JRuby agrega todas as vantagens consagradas da plataforma Java à tecnologia Ruby/Rails. 164
  165. 165. Últimas palavras... A equação Ruby + Rails + Java pode colocar o Rails no mercado corporativo dominado pela cultura Java. 165
  166. 166. Últimas palavras... Isso definitivamente pode ser a próxima grande onda do mercado de desenvolvimento de software. 166
  167. 167. Últimas palavras... Fique atento.... ;-) 167
  168. 168. P&R blog.seatecnologia.com.br alexandre.gomes@seatecnologia.com.br twitter.com/alegomes

×