SlideShare uma empresa Scribd logo
1 de 42
Baixar para ler offline
Introdução ao Ruby on Rails




           Introdução ao Ruby on Rails
Introdução ao Ruby on Rails > Palestrante




           Juan Maiz Lulkin Flores da Cunha
                    WWR person/9354
                    vice-campeão mundial de
                    defender of the favicon
Introdução ao Ruby on Rails > História




           História
                    David Heinemeier Hanson (DHH)
                    Martin Fowler
                    37Signals
Introdução ao Ruby on Rails > Ruby on Rails




           Ruby on Rails
                   Ruby
                   Model View Controller
                   Princípios
                   Comunidade
                   And so much more
Introdução ao Ruby on Rails > Ruby on Rails > Ruby




           Ruby
                   Smalltalk
                      elegância conceitual
                   Python
                      facilidade de uso
                   Perl
                      pragmatismo
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Smalltalk




           Smalltalk
                   1 + 1
                       => 2
                   1.+(1)
                       => 2
                   1.send('+',1)
                       => 2
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Python




           Python
                   for 1 in 1..10
                      puts i
                   end
                      1
                      2
                      3
                      4
                      5
                      6
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Perl




           Perl
                   ls = %w{smalltalk python perl}
                       => ["smalltalk", "python", "perl"]
                   ls.map{|l| “Ruby é como #{l}. ” }.join
                       => “Ruby é como smalltalk. Ruby é como
                              python. Ruby é como perl.
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Hello




           Ruby
                   5.times{ p “ybuR olleH”.reverse }
                      "Hello Ruby"
                      "Hello Ruby"
                      "Hello Ruby"
                      "Hello Ruby"
                      "Hello Ruby"
                      => 5
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos




           Ruby
                   Totalmente OO
                   Mixins (toma essa!)
                   Classes “abertas”
                   Blocos
                   Bibliotecas
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Totalmente OO




          Totalmente OO
                   42.class
                      => Fixnum
                   Fixnum.class
                      => Class
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Mixins (toma essa!)




           Mixins (toma essa!)
                   module Cool
                       def is_cool!
                        “#{self} is cool!”
                       end
                   end
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Classes “abertas”




           Classes “abertas”
                   class String
                       include Cool
                   end
                   puts “Ruby”.is_cool!
                      Ruby is cool!
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Blocos




           Blocos
                   [16,19,21,15].select{|n| n > 17}
                      => [19,21]
                   [1,2,3].map{|n| n*2 }
                      => [2,4,6]
                   [5,6,7,8].sort_by{ … }
                   File.open('file.txt').each_line{ … }
                   Dir.glob('*.rb').each{ … }
                   Benchmark.measure { ... }
Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Bibliotecas




           Bibliotecas
                   Hpricot + OpenUri
                   Hpricot(open 'http://ab.com').search('a').map{|a| a[:href]}
                   Prawn
                   Prawn::Document.new.text(“Hello PDF”)
                   RedCloth
                   RedCloth.new(“Hello *Textile*”).to_html
                   RMagick
                   Image.read('i.pdf').first.write('i.png'){self.quality = 80}
                   Shoes
                   Shoes.app{ button "Hello Windows" }
                   RubyGame
                   Game.new.when_key_pressed(:q){ exit }
                   Geokit
                   YahooGeocoder.geocode 'Rua Vieira de Casto 262'
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller




           Model View Controller
                   Model
                       dados e lógica de domínio
                   View
                       interface
                   Controller
                       caminhos e distribuição
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model




           Model
                   ActiveRecord
                   Migrações
                   Operações básicas
                   Relações
                   Validações
                   Acts as
                   Named scopes
                   Adicionar métodos
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Migrações




           Migrações
                   class CreateEvents < ActiveRecord::Migration
                      def self.up
                         create_table :events do |t|
                            t.string :name, :null => false
                            t.boolean :active, :default => true
                            t.integer :year, :null => false
                            t.timestamps
                         end
                      end
                   end
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas




           Operações básicas
                   Insert
                   Event.create :name => 'RS on Rails',
                                                :year => Date.today.year
                   e = Event.new
                   e.name = 'RS on Rails'
                   e.year = 2009
                   e.save
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas




           Operações básicas
                   Select
                   Event.all :conditions => 'active',
                                             :order => 'created_at',
                                             :limit => 10
                   e = Event.first
                   e = Event.find 1
                   e = Event.find_by_name 'RS on Rails'
                   e = Event.find_by_year 2009
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas




           Operações básicas
                   Update
                   Event.update_all 'active = true'
                   e = Event.first
                   e.name = 'other name'
                   e.save
                   e.update_attribute :active => false
                   e.toggle! :active
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas




           Operações básicas
                   Delete
                   Event.delete_all
                   e = Event.first
                   e.destroy
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações




           Relações
                   class Event < ActiveRecord::Base
                       has_many :talks
                   end
                   class Talk < ActiveRecord::Base
                       belongs_to :event
                       has_one :speaker
                   end
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações




           Relações
                   rsr = Event.find_by_name('rsrails')
                   talk = rsr.talks.first
                   talk.name
                       => “Introdução ao Ruby on Rails”
                   talk.speaker.name
                       => “Juan Maiz Lulkin”
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Validações




           Validações
                   class Event < ActiveRecord::Base
                      validates_presence_of :name, :year
                      validates_numericality_of :year
                      validates_inclusion_of :year,
                                                          :in => 2009..2099
                      validates_length_of :name,
                                                          :minimum => 4
                      validates_format_of :name,
                                                          :with => /[A-Z]d+/
                   end
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as




           Acts As
                   class Category < ActiveRecord::Base
                       acts_as_tree
                   enb
                   Category.find(10).parent
                   Category.find(20).children
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as




           Acts As
                   class Doc < ActiveRecord::Base
                      acts_as_versioned
                   end
                   doc = Doc.create :name = '1 st name'
                   doc.version
                     => 1

                   doc.update_attribute :name, '2 nd name'
                   doc.version
                     => 2

                   doc.revert_to(1)
                   doc.name
                     => 1 st name
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Named scopes




           Named scopes
                   class Product < ActiveRecord::Base
                     named_scope :top, :order => 'rank desc'
                     named_scope :ten, :limit => 10
                     named_scope :between, lambda{|min,max|
                          {:conditions => [“price between ? and ?”, min, max]}}
                   end
                   Product.between(0,100).top.ten
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Adicionar métodos




           Adicionar métodos
                   class Product < ActiveRecord::Base
                       def +(product)
                        price + product.price
                       end
                   end
                   foo = Product.find(1)
                   bar = Product.find(2)
                   foo + bar
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Controller




           Controller
                    URL: http://seusite.com/events/rsrails


                    class EventsController < ApplicationController
                      def show
                         name = params[:id]
                         @event = Event.find_by_name(name)
                      end
                    end
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > View




           View
                   app/views/events/show.html.haml


                       #content
                       %h1 Palestras
                       %ul
                          - for talk in @event.talks
                            %li= talk.title

                                                * Você está usando HAML, não?
Introdução ao Ruby on Rails > Ruby on Rails > Princípios




           Princípios
                    Convention Over Configuration
                      Se é usado na maior parte dos
                      casos, deve ser o padrão.
                    Don't Repeat Yourself
                       Mixins, plugins, engines, gems...
                    Métodos ágeis
                       BDD, TDD, integração contínua,
                      deployment...
Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC




           Convention Over Configuration
                   XML YAML
                   development:
                       adapter: postgresql
                       encoding: unicode
                       database: events_development
                       pool: 5
                       username: event_admin
                       password: *****
Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC




           Convention Over Configuration
                   rsrails = Event.find(1)
                       => assume campo “id” na tabela “events”
                   rsrails.talks
                       => assume uma tabela “talks” com um
                      fk “event_id”
                   rsrails.talks.first.speaker
                       => assume campo “speaker_id” em “talks”
                             como fk para tabela “speakers”
Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC




           Convention Over Configuration
                   script/generate scaffold Event
                                                                 name:string
                                                                 year:integer
                                                                 active:boolean
Introdução ao Ruby on Rails > Ruby on Rails > Princípios > DRY




           Don't Repeat Yourself
                   active_scaffold
                   link_to login
                   image_tag 'star.png' * hotel.stars
                   render :partial => 'event',
                                               :collection => @events
Introdução ao Ruby on Rails > Ruby on Rails > Princípios > Métodos ágeis




           Métodos ágeis
                   class EventTest < ActiveSupport::TestCase
                      test "creation" do
                         assert Event.create :name => 'rsrails',
                                                                     :year => 2009
                      end
                   end
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis




           Métodos ágeis
                    rake integrate
                    cap deploy
Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis




           Métodos ágeis
                    Getting Real
                    http://gettingreal.37signals.com/
Introdução ao Ruby on Rails > Ruby on Rails > Comunidade




          Comunidade
                   Lista rails-br
                   Ruby Inside (.com e .com.br)
                   Working With Rails
Introdução ao Ruby on Rails > Ruby on Rails > And so much more




          And so much more
                   Internacionalização (i18n)
                   Rotas
                   Cache
                   Ajax
                   Background Jobs
                   ...
Introdução ao Ruby on Rails > Fim




           Fim

Mais conteúdo relacionado

Mais procurados

Slide Aula - Curso CakePHP
Slide Aula - Curso CakePHPSlide Aula - Curso CakePHP
Slide Aula - Curso CakePHPRangel Javier
 
Introducao ao desenvolvimento web com Rails
Introducao ao desenvolvimento web com RailsIntroducao ao desenvolvimento web com Rails
Introducao ao desenvolvimento web com RailsKaton Agência Digital
 
Minicurso Ruby on Rails - Wake Up Systems
Minicurso Ruby on Rails - Wake Up SystemsMinicurso Ruby on Rails - Wake Up Systems
Minicurso Ruby on Rails - Wake Up SystemsWakeUpSystems
 
CakePHP e o desenvolvimento rápido
CakePHP e o desenvolvimento rápidoCakePHP e o desenvolvimento rápido
CakePHP e o desenvolvimento rápidoIvan Rosolen
 
Ruby on Rails: um estudo de viabilidade em ambientes empresariais
Ruby on Rails: um estudo de viabilidade em ambientes empresariaisRuby on Rails: um estudo de viabilidade em ambientes empresariais
Ruby on Rails: um estudo de viabilidade em ambientes empresariaisRodrigo Recio
 
CakePHP - Aprendendo a fazer o primeiro bolo
CakePHP - Aprendendo a fazer o primeiro boloCakePHP - Aprendendo a fazer o primeiro bolo
CakePHP - Aprendendo a fazer o primeiro boloelliando dias
 
Aula 1 - curso java web - JSP Java Server Page
Aula 1 - curso java web - JSP Java Server PageAula 1 - curso java web - JSP Java Server Page
Aula 1 - curso java web - JSP Java Server PageEvandro Júnior
 
Minicurso Ruby e Rails (RailsMG UNA)
Minicurso Ruby e Rails (RailsMG UNA)Minicurso Ruby e Rails (RailsMG UNA)
Minicurso Ruby e Rails (RailsMG UNA)Daniel Lopes
 
Palestra Desenvolvimento Ágil para Web com ROR UVA
Palestra Desenvolvimento Ágil para Web com ROR UVAPalestra Desenvolvimento Ágil para Web com ROR UVA
Palestra Desenvolvimento Ágil para Web com ROR UVAThiago Cifani
 
Doctrine 2 camada de persistência para php
Doctrine 2   camada de persistência para phpDoctrine 2   camada de persistência para php
Doctrine 2 camada de persistência para phpFabio B. Silva
 
Mini-curso RubyOnRails CESOL
Mini-curso RubyOnRails CESOLMini-curso RubyOnRails CESOL
Mini-curso RubyOnRails CESOLtarginosilveira
 
Linguagem PHP para principiantes
Linguagem PHP para principiantesLinguagem PHP para principiantes
Linguagem PHP para principiantesMarco Pinheiro
 
Introdução à Servlets e JSP
Introdução à Servlets e JSPIntrodução à Servlets e JSP
Introdução à Servlets e JSPledsifes
 
WebService Restful em Java
WebService Restful em JavaWebService Restful em Java
WebService Restful em Javaalexmacedo
 

Mais procurados (20)

Slide Aula - Curso CakePHP
Slide Aula - Curso CakePHPSlide Aula - Curso CakePHP
Slide Aula - Curso CakePHP
 
Introducao ao desenvolvimento web com Rails
Introducao ao desenvolvimento web com RailsIntroducao ao desenvolvimento web com Rails
Introducao ao desenvolvimento web com Rails
 
Minicurso Ruby on Rails - Wake Up Systems
Minicurso Ruby on Rails - Wake Up SystemsMinicurso Ruby on Rails - Wake Up Systems
Minicurso Ruby on Rails - Wake Up Systems
 
Servlets e jsp
Servlets e jspServlets e jsp
Servlets e jsp
 
CakePHP e o desenvolvimento rápido
CakePHP e o desenvolvimento rápidoCakePHP e o desenvolvimento rápido
CakePHP e o desenvolvimento rápido
 
Ruby on Rails: um estudo de viabilidade em ambientes empresariais
Ruby on Rails: um estudo de viabilidade em ambientes empresariaisRuby on Rails: um estudo de viabilidade em ambientes empresariais
Ruby on Rails: um estudo de viabilidade em ambientes empresariais
 
CakePHP - Aprendendo a fazer o primeiro bolo
CakePHP - Aprendendo a fazer o primeiro boloCakePHP - Aprendendo a fazer o primeiro bolo
CakePHP - Aprendendo a fazer o primeiro bolo
 
Servlets e JSP
Servlets e JSPServlets e JSP
Servlets e JSP
 
Aula 1 - curso java web - JSP Java Server Page
Aula 1 - curso java web - JSP Java Server PageAula 1 - curso java web - JSP Java Server Page
Aula 1 - curso java web - JSP Java Server Page
 
Minicurso Ruby e Rails (RailsMG UNA)
Minicurso Ruby e Rails (RailsMG UNA)Minicurso Ruby e Rails (RailsMG UNA)
Minicurso Ruby e Rails (RailsMG UNA)
 
Servlets e JSP
Servlets e JSPServlets e JSP
Servlets e JSP
 
Palestra Desenvolvimento Ágil para Web com ROR UVA
Palestra Desenvolvimento Ágil para Web com ROR UVAPalestra Desenvolvimento Ágil para Web com ROR UVA
Palestra Desenvolvimento Ágil para Web com ROR UVA
 
Java web
Java webJava web
Java web
 
Doctrine 2 camada de persistência para php
Doctrine 2   camada de persistência para phpDoctrine 2   camada de persistência para php
Doctrine 2 camada de persistência para php
 
Mini-curso RubyOnRails CESOL
Mini-curso RubyOnRails CESOLMini-curso RubyOnRails CESOL
Mini-curso RubyOnRails CESOL
 
Linguagem PHP para principiantes
Linguagem PHP para principiantesLinguagem PHP para principiantes
Linguagem PHP para principiantes
 
Introdução à Servlets e JSP
Introdução à Servlets e JSPIntrodução à Servlets e JSP
Introdução à Servlets e JSP
 
WebService Restful em Java
WebService Restful em JavaWebService Restful em Java
WebService Restful em Java
 
Curso de JSP
Curso de JSPCurso de JSP
Curso de JSP
 
JSPs Introdução Parte 1
JSPs Introdução Parte 1JSPs Introdução Parte 1
JSPs Introdução Parte 1
 

Destaque

Dando os primeiros passos com rails
Dando os primeiros passos com railsDando os primeiros passos com rails
Dando os primeiros passos com railsMarcos Sousa
 
O que vem por aí com Rails 3
O que vem por aí com Rails 3O que vem por aí com Rails 3
O que vem por aí com Rails 3Frevo on Rails
 
What is-google-adwords
What is-google-adwordsWhat is-google-adwords
What is-google-adwordsAnthony Greene
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railsousli07
 

Destaque (6)

RubyonRails
RubyonRailsRubyonRails
RubyonRails
 
Creating Android apps
Creating Android appsCreating Android apps
Creating Android apps
 
Dando os primeiros passos com rails
Dando os primeiros passos com railsDando os primeiros passos com rails
Dando os primeiros passos com rails
 
O que vem por aí com Rails 3
O que vem por aí com Rails 3O que vem por aí com Rails 3
O que vem por aí com Rails 3
 
What is-google-adwords
What is-google-adwordsWhat is-google-adwords
What is-google-adwords
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 

Semelhante a Introdução ao Ruby on Rails

Desenvolvimento ágil de software com Ruby on Rails
Desenvolvimento ágil de software com Ruby on RailsDesenvolvimento ágil de software com Ruby on Rails
Desenvolvimento ágil de software com Ruby on RailsLucas Caton
 
Introdução ao Ruby on Rails
Introdução ao Ruby on RailsIntrodução ao Ruby on Rails
Introdução ao Ruby on RailsJuan Maiz
 
Quick introduction to Ruby on Rails
Quick introduction to Ruby on RailsQuick introduction to Ruby on Rails
Quick introduction to Ruby on RailsWhitesmith
 
Ruby and Rails intro
Ruby and Rails introRuby and Rails intro
Ruby and Rails introNuno Silva
 
Ruby on Rails Colocando a web nos trilhos
Ruby on Rails Colocando a web nos trilhosRuby on Rails Colocando a web nos trilhos
Ruby on Rails Colocando a web nos trilhosjpaulolins
 
ruby on rails e o mercado
ruby on rails e o mercadoruby on rails e o mercado
ruby on rails e o mercadoelliando dias
 
Rails - EXATEC2009
Rails - EXATEC2009Rails - EXATEC2009
Rails - EXATEC2009Caue Guerra
 
Esta começando a programar para a web? Então começe com Rails
Esta começando a programar para a web? Então começe com RailsEsta começando a programar para a web? Então começe com Rails
Esta começando a programar para a web? Então começe com Railsismaelstahelin
 
Introdução ao Ruby
Introdução ao RubyIntrodução ao Ruby
Introdução ao RubyMilton Moura
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Railshome
 
Testes Automatizados em Ruby on Rails
Testes Automatizados em Ruby on RailsTestes Automatizados em Ruby on Rails
Testes Automatizados em Ruby on RailsThiago Cifani
 
A linguagem Ruby e o framework Rails
A linguagem Ruby e o framework RailsA linguagem Ruby e o framework Rails
A linguagem Ruby e o framework Railss4nx
 
Slides do curso Programação web com RubyOnRails
Slides do curso Programação web com RubyOnRailsSlides do curso Programação web com RubyOnRails
Slides do curso Programação web com RubyOnRailsTiago Godinho
 
Ruby on Rails e o Mercado
Ruby on Rails e o MercadoRuby on Rails e o Mercado
Ruby on Rails e o MercadoJulio Monteiro
 
Introdução ao Rails (Linguagil)
Introdução ao Rails (Linguagil)Introdução ao Rails (Linguagil)
Introdução ao Rails (Linguagil)Daniel Lopes
 
Minicurso de Rails - WTISC 2014
Minicurso de Rails - WTISC 2014Minicurso de Rails - WTISC 2014
Minicurso de Rails - WTISC 2014Zarathon Maia
 

Semelhante a Introdução ao Ruby on Rails (20)

RoR na prática
RoR na práticaRoR na prática
RoR na prática
 
Desenvolvimento ágil de software com Ruby on Rails
Desenvolvimento ágil de software com Ruby on RailsDesenvolvimento ágil de software com Ruby on Rails
Desenvolvimento ágil de software com Ruby on Rails
 
Introdução ao Ruby on Rails
Introdução ao Ruby on RailsIntrodução ao Ruby on Rails
Introdução ao Ruby on Rails
 
Quick introduction to Ruby on Rails
Quick introduction to Ruby on RailsQuick introduction to Ruby on Rails
Quick introduction to Ruby on Rails
 
Ruby and Rails intro
Ruby and Rails introRuby and Rails intro
Ruby and Rails intro
 
Ruby e Rails
Ruby e RailsRuby e Rails
Ruby e Rails
 
Ruby on Rails Colocando a web nos trilhos
Ruby on Rails Colocando a web nos trilhosRuby on Rails Colocando a web nos trilhos
Ruby on Rails Colocando a web nos trilhos
 
ruby on rails e o mercado
ruby on rails e o mercadoruby on rails e o mercado
ruby on rails e o mercado
 
Rails - EXATEC2009
Rails - EXATEC2009Rails - EXATEC2009
Rails - EXATEC2009
 
Esta começando a programar para a web? Então começe com Rails
Esta começando a programar para a web? Então começe com RailsEsta começando a programar para a web? Então começe com Rails
Esta começando a programar para a web? Então começe com Rails
 
Introdução ao Ruby
Introdução ao RubyIntrodução ao Ruby
Introdução ao Ruby
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Testes Automatizados em Ruby on Rails
Testes Automatizados em Ruby on RailsTestes Automatizados em Ruby on Rails
Testes Automatizados em Ruby on Rails
 
A linguagem Ruby e o framework Rails
A linguagem Ruby e o framework RailsA linguagem Ruby e o framework Rails
A linguagem Ruby e o framework Rails
 
Slides do curso Programação web com RubyOnRails
Slides do curso Programação web com RubyOnRailsSlides do curso Programação web com RubyOnRails
Slides do curso Programação web com RubyOnRails
 
Ruby on Rails e o Mercado
Ruby on Rails e o MercadoRuby on Rails e o Mercado
Ruby on Rails e o Mercado
 
Introdução ao Rails (Linguagil)
Introdução ao Rails (Linguagil)Introdução ao Rails (Linguagil)
Introdução ao Rails (Linguagil)
 
Minicurso de Rails - WTISC 2014
Minicurso de Rails - WTISC 2014Minicurso de Rails - WTISC 2014
Minicurso de Rails - WTISC 2014
 
Ruby & Rails
Ruby & RailsRuby & Rails
Ruby & Rails
 
Ruby on rails
Ruby on railsRuby on rails
Ruby on rails
 

Mais de Juan Maiz

Reasoning about Code with React
Reasoning about Code with ReactReasoning about Code with React
Reasoning about Code with ReactJuan Maiz
 
Code reviews
Code reviewsCode reviews
Code reviewsJuan Maiz
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-phpJuan Maiz
 
Ruby para programadores PHP
Ruby para programadores PHPRuby para programadores PHP
Ruby para programadores PHPJuan Maiz
 
SaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brSaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brJuan Maiz
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbJuan Maiz
 
rails_and_agile
rails_and_agilerails_and_agile
rails_and_agileJuan Maiz
 

Mais de Juan Maiz (10)

Reasoning about Code with React
Reasoning about Code with ReactReasoning about Code with React
Reasoning about Code with React
 
Code reviews
Code reviewsCode reviews
Code reviews
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
Ruby para-programadores-php
Ruby para-programadores-phpRuby para-programadores-php
Ruby para-programadores-php
 
Ruby para programadores PHP
Ruby para programadores PHPRuby para programadores PHP
Ruby para programadores PHP
 
SaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.brSaaS - RubyMastersConf.com.br
SaaS - RubyMastersConf.com.br
 
Saas
SaasSaas
Saas
 
Tree top
Tree topTree top
Tree top
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
rails_and_agile
rails_and_agilerails_and_agile
rails_and_agile
 

Introdução ao Ruby on Rails

  • 1. Introdução ao Ruby on Rails Introdução ao Ruby on Rails
  • 2. Introdução ao Ruby on Rails > Palestrante Juan Maiz Lulkin Flores da Cunha WWR person/9354 vice-campeão mundial de defender of the favicon
  • 3. Introdução ao Ruby on Rails > História História David Heinemeier Hanson (DHH) Martin Fowler 37Signals
  • 4. Introdução ao Ruby on Rails > Ruby on Rails Ruby on Rails Ruby Model View Controller Princípios Comunidade And so much more
  • 5. Introdução ao Ruby on Rails > Ruby on Rails > Ruby Ruby Smalltalk elegância conceitual Python facilidade de uso Perl pragmatismo
  • 6. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Smalltalk Smalltalk 1 + 1 => 2 1.+(1) => 2 1.send('+',1) => 2
  • 7. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Python Python for 1 in 1..10 puts i end 1 2 3 4 5 6
  • 8. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Perl Perl ls = %w{smalltalk python perl} => ["smalltalk", "python", "perl"] ls.map{|l| “Ruby é como #{l}. ” }.join => “Ruby é como smalltalk. Ruby é como python. Ruby é como perl.
  • 9. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Hello Ruby 5.times{ p “ybuR olleH”.reverse } "Hello Ruby" "Hello Ruby" "Hello Ruby" "Hello Ruby" "Hello Ruby" => 5
  • 10. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos Ruby Totalmente OO Mixins (toma essa!) Classes “abertas” Blocos Bibliotecas
  • 11. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Totalmente OO Totalmente OO 42.class => Fixnum Fixnum.class => Class
  • 12. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Mixins (toma essa!) Mixins (toma essa!) module Cool def is_cool! “#{self} is cool!” end end
  • 13. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Classes “abertas” Classes “abertas” class String include Cool end puts “Ruby”.is_cool! Ruby is cool!
  • 14. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Blocos Blocos [16,19,21,15].select{|n| n > 17} => [19,21] [1,2,3].map{|n| n*2 } => [2,4,6] [5,6,7,8].sort_by{ … } File.open('file.txt').each_line{ … } Dir.glob('*.rb').each{ … } Benchmark.measure { ... }
  • 15. Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Bibliotecas Bibliotecas Hpricot + OpenUri Hpricot(open 'http://ab.com').search('a').map{|a| a[:href]} Prawn Prawn::Document.new.text(“Hello PDF”) RedCloth RedCloth.new(“Hello *Textile*”).to_html RMagick Image.read('i.pdf').first.write('i.png'){self.quality = 80} Shoes Shoes.app{ button "Hello Windows" } RubyGame Game.new.when_key_pressed(:q){ exit } Geokit YahooGeocoder.geocode 'Rua Vieira de Casto 262'
  • 16. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller Model View Controller Model dados e lógica de domínio View interface Controller caminhos e distribuição
  • 17. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model Model ActiveRecord Migrações Operações básicas Relações Validações Acts as Named scopes Adicionar métodos
  • 18. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Migrações Migrações class CreateEvents < ActiveRecord::Migration def self.up create_table :events do |t| t.string :name, :null => false t.boolean :active, :default => true t.integer :year, :null => false t.timestamps end end end
  • 19. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas Operações básicas Insert Event.create :name => 'RS on Rails', :year => Date.today.year e = Event.new e.name = 'RS on Rails' e.year = 2009 e.save
  • 20. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas Operações básicas Select Event.all :conditions => 'active', :order => 'created_at', :limit => 10 e = Event.first e = Event.find 1 e = Event.find_by_name 'RS on Rails' e = Event.find_by_year 2009
  • 21. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas Operações básicas Update Event.update_all 'active = true' e = Event.first e.name = 'other name' e.save e.update_attribute :active => false e.toggle! :active
  • 22. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas Operações básicas Delete Event.delete_all e = Event.first e.destroy
  • 23. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações Relações class Event < ActiveRecord::Base has_many :talks end class Talk < ActiveRecord::Base belongs_to :event has_one :speaker end
  • 24. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações Relações rsr = Event.find_by_name('rsrails') talk = rsr.talks.first talk.name => “Introdução ao Ruby on Rails” talk.speaker.name => “Juan Maiz Lulkin”
  • 25. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Validações Validações class Event < ActiveRecord::Base validates_presence_of :name, :year validates_numericality_of :year validates_inclusion_of :year, :in => 2009..2099 validates_length_of :name, :minimum => 4 validates_format_of :name, :with => /[A-Z]d+/ end
  • 26. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as Acts As class Category < ActiveRecord::Base acts_as_tree enb Category.find(10).parent Category.find(20).children
  • 27. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as Acts As class Doc < ActiveRecord::Base acts_as_versioned end doc = Doc.create :name = '1 st name' doc.version => 1 doc.update_attribute :name, '2 nd name' doc.version => 2 doc.revert_to(1) doc.name => 1 st name
  • 28. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Named scopes Named scopes class Product < ActiveRecord::Base named_scope :top, :order => 'rank desc' named_scope :ten, :limit => 10 named_scope :between, lambda{|min,max| {:conditions => [“price between ? and ?”, min, max]}} end Product.between(0,100).top.ten
  • 29. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Adicionar métodos Adicionar métodos class Product < ActiveRecord::Base def +(product) price + product.price end end foo = Product.find(1) bar = Product.find(2) foo + bar
  • 30. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Controller Controller URL: http://seusite.com/events/rsrails class EventsController < ApplicationController def show name = params[:id] @event = Event.find_by_name(name) end end
  • 31. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > View View app/views/events/show.html.haml #content %h1 Palestras %ul - for talk in @event.talks %li= talk.title * Você está usando HAML, não?
  • 32. Introdução ao Ruby on Rails > Ruby on Rails > Princípios Princípios Convention Over Configuration Se é usado na maior parte dos casos, deve ser o padrão. Don't Repeat Yourself Mixins, plugins, engines, gems... Métodos ágeis BDD, TDD, integração contínua, deployment...
  • 33. Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC Convention Over Configuration XML YAML development: adapter: postgresql encoding: unicode database: events_development pool: 5 username: event_admin password: *****
  • 34. Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC Convention Over Configuration rsrails = Event.find(1) => assume campo “id” na tabela “events” rsrails.talks => assume uma tabela “talks” com um fk “event_id” rsrails.talks.first.speaker => assume campo “speaker_id” em “talks” como fk para tabela “speakers”
  • 35. Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC Convention Over Configuration script/generate scaffold Event name:string year:integer active:boolean
  • 36. Introdução ao Ruby on Rails > Ruby on Rails > Princípios > DRY Don't Repeat Yourself active_scaffold link_to login image_tag 'star.png' * hotel.stars render :partial => 'event', :collection => @events
  • 37. Introdução ao Ruby on Rails > Ruby on Rails > Princípios > Métodos ágeis Métodos ágeis class EventTest < ActiveSupport::TestCase test "creation" do assert Event.create :name => 'rsrails', :year => 2009 end end
  • 38. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis Métodos ágeis rake integrate cap deploy
  • 39. Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis Métodos ágeis Getting Real http://gettingreal.37signals.com/
  • 40. Introdução ao Ruby on Rails > Ruby on Rails > Comunidade Comunidade Lista rails-br Ruby Inside (.com e .com.br) Working With Rails
  • 41. Introdução ao Ruby on Rails > Ruby on Rails > And so much more And so much more Internacionalização (i18n) Rotas Cache Ajax Background Jobs ...
  • 42. Introdução ao Ruby on Rails > Fim Fim