SlideShare uma empresa Scribd logo
1 de 104
Rails 3
José Valim
Trabalho na
Plataforma Tecnologia
Autor de diversos
projetos open source
Rails Core
Rails 3
Rails 3
OMG! Isso é incrível!
Mais rápido
Agnóstico
Modular
Mas vocês já ouviram
    sobre isso...
Como Rails 3 mudará o
modo que desenvolvemos
      aplicações?
#1
Bundler
“can't activate activesupport (= 2.3.4,
      runtime), already activated
activesupport-2.3.5 (Gem::Exception)”
#1
require “activesupport”
}
                                Rubygems
#1                             carregará a
require “activesupport”       última versão:
                                   2.3.5
}
                                 Rubygems
#1                              carregará a
require “activesupport”        última versão:
                                    2.3.5


#2
gem “activesupport”, “2.3.4”
Boom!
OMG! Isso NÃO é incrível!
# Gem le
source 'http://gemcutter.org'

gem 'rails', ' 3.0.0 '
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'ruby-debug'
Bundler resolve
dependências e faz um
“lock” do seu load path
Bundler resolve
dependências e faz um
“lock” do seu load path
Bundler resolve
dependências e faz um
“lock” do seu load path
}
#1
activesupport-2.2.2
activesupport-2.3.4       Filesystem
activesupport-2.3.5
}
#1
activesupport-2.2.2
activesupport-2.3.4                Filesystem
activesupport-2.3.5


                               }
#2
gem “activesupport”, “2.3.4”       Gemfile
}
#1
activesupport-2.2.2
activesupport-2.3.4                Filesystem
activesupport-2.3.5


                               }
#2
gem “activesupport”, “2.3.4”       Gemfile




                               }
#3
activesupport-2.3.4                $LOAD_PATH
Bundler garante que
todos no mesmo projeto
   usam as mesmas
     dependências
Gerenciamento de dependências
        OMG! Isso é incrível!
#2
respond_with
Rails 2.3
def index
  @users = User.all

  respond_to do |format|
    format.html # index.html.erb
    format.xml { render :xml => @users }
  end
end
Rails 3

respond_to :html, :xml

def index
  @users = User.all
  respond_with(@users)
end
Rails 3

respond_to :html, :xml

def index
  @users = User.all       Formato de
  respond_with(@users)    navegação
end
Rails 3

respond_to :html, :xml

def index                 Formato
  @users = User.all        de API
  respond_with(@users)
end
Navegação   API

 GET


POST



 PUT


DELETE
Navegação   API

 GET


POST



 PUT


DELETE
Navegação   API

 GET


POST



 PUT


DELETE
def index
  @users = User.all

  respond_to do |format|
    format.html # index.html.erb
    format.xml { render :xml => @users }
  end
end
Navegação       API

 GET     render template


POST



 PUT


DELETE
def index
  @users = User.all

  respond_to do |format|
    format.html # index.html.erb
    format.xml { render :xml => @users }
  end
end
Navegação              API
                                 render
 GET     render template
                           resources.to_format


POST



 PUT


DELETE
def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to(@user, :notice => 'User was
successfully created.') }
      format.xml { render :xml => @user, :status
=> :created, :location => @user }
    else
      format.html { render :action => "new" }
      format.xml { render :xml => @user.errors, :status
=> :unprocessable_entity }
    end
  end
end
Navegação              API
                                          render
       GET        render template
                                    resources.to_format
        Success
POST
        Failure


       PUT


   DELETE
if @user.save
  format.html { redirect_to(@user, :notice => 'User
was successfully created.') }
  format.xml { render :xml => @user, :status
=> :created, :location => @user }
Navegação                 API
                                               render
       GET         render template
                                         resources.to_format
        Success   redirect_to resource
POST
        Failure


       PUT


   DELETE
if @user.save
  format.html { redirect_to(@user, :notice => 'User
was successfully created.') }
  format.xml { render :xml => @user, :status
=> :created, :location => @user }
Navegação                 API
                                                render
       GET         render template
                                         resources.to_format
                                                render
        Success   redirect_to resource
                                          resource.to_format
POST
        Failure


       PUT


   DELETE
else
  format.html { render :action => "new" }
  format.xml { render :xml =>
@user.errors, :status => :unprocessable_entity }
Navegação                   API
                                                render
       GET         render template
                                         resources.to_format
                                                render
        Success   redirect_to resource
                                          resource.to_format
POST
        Failure       render :new        render resource.errors


       PUT


   DELETE
Navegação                    API
                                                  render
       GET          render template
                                           resources.to_format
                                                  render
        Success   redirect_to resource
                                            resource.to_format
POST
        Failure       render :new          render resource.errors

        Success   redirect_to resource           head :ok
PUT
        Failure        render :edit        render resource.errors

   DELETE         redirect_to collection         head :ok
Três variáveis

     Verbo HTTP
  Estado do recurso
Formato da requisição
respond_with(@user)
respond_with(@user)

 ActionController::Responder
respond_with(@user)

 ActionController::Responder




                                 Navegação                 API

                                                          render
                 GET          render template
                                                    resources.to_format
                                                          render
                  Success    redirect_to resource
                                                    resource.to_format
          POST
                                                          render
                   Failure       render :new
                                                      resource.errors

                  Success    redirect_to resource        head :ok
          PUT
                                                          render
                   Failure       render :edit
                                                      resource.errors
                                 redirect_to
             DELETE                                      head :ok
                                  collection
respond_with(@user)

 ActionController::Responder

                                                tabela em código


                                 Navegação                 API

                                                          render
                 GET          render template
                                                    resources.to_format
                                                          render
                  Success    redirect_to resource
                                                    resource.to_format
          POST
                                                          render
                   Failure       render :new
                                                      resource.errors

                  Success    redirect_to resource        head :ok
          PUT
                                                          render
                   Failure       render :edit
                                                      resource.errors
                                 redirect_to
             DELETE                                      head :ok
                                  collection
def create
  @user = User.new(params[:user])

  respond_to do |format|
    if @user.save
      format.html { redirect_to(@user, :notice => 'User was
successfully created.') }
      format.xml { render :xml => @user, :status
=> :created, :location => @user }
    else
      format.html { render :action => "new" }
      format.xml { render :xml => @user.errors, :status
=> :unprocessable_entity }
    end
  end
end
def create
  @user = User.new(params[:user])
  flash[:user] = 'User was successfully created.' if @user.save
  respond_with(@user)
end
Navegação                    API
                                                  render
       GET          render template
                                           resources.to_format
                                                  render
        Success   redirect_to resource
                                            resource.to_format
POST
        Failure       render :new          render resource.errors

        Success   redirect_to resource           head :ok
PUT
        Failure        render :edit        render resource.errors

   DELETE         redirect_to collection         head :ok
Navegação                    API
                                                  render
       GET          render template
                                           resources.to_format
                                                  render
        Success   redirect_to resource
                                            resource.to_format
POST
        Failure       render :new          render resource.errors

        Success   redirect_to resource           head :ok
PUT
        Failure        render :edit        render resource.errors

   DELETE         redirect_to collection         head :ok
Navegação                    API
                                                render
       GET          render template
                                         resources.to_format
                                                render
        Success   redirect_to collection
                                          resource.to_format
POST
        Failure       render :new          render resource.errors

        Success   redirect_to collection         head :ok
PUT
        Failure        render :edit        render resource.errors

   DELETE         redirect_to collection         head :ok
Rails 2.3

a) Senta e chora
b) Mata o cliente
Rails 3

a) Senta e chora
b) Mata o cliente
c) Crie o seu responder
DRY
OMG! Isso é incrível!
#3
ARel
Rails 2.3


cars = Car.all(:conditions => { :color => 'black'})

expensive_cars = Car.all(:conditions => { :colour =>
'black'}, :order => 'cars.price DESC', :limit => 10)
Rails 3

cars = Car.where(:color => 'black')

expensive_cars = cars.
  order('cars.price DESC').limit(10)
Rails 3

# controller
@cars = Car.where(:color => 'black')

# view
<% cache do %>
  <% @cars.each do |car| %>
    <%= car.name %>
  <% end %>
<% end %>
Rails 3
                   Não acessa o
                  banco de dados
# controller
@cars = Car.where(:color => 'black')

# view
<% cache do %>
  <% @cars.each do |car| %>
    <%= car.name %>
  <% end %>
<% end %>
Rails 3
                   Não acessa o
                  banco de dados
# controller
@cars = Car.where(:color => 'black')
                       Acessa o
# view
                    banco de dados
<% cache do %>
  <% @cars.each do |car| %>
    <%= car.name %>
  <% end %>
<% end %>
Melhor e mais rápido!
    OMG! Isso é incrível!
#4
ActiveSupport::Noti cations
É o “Facebook news
feed” da sua aplicação
ActiveSupport::Notifications.
  instrument "active_record.sql" do
  # query the database adapter
end
ActiveSupport::Notifications.
  subscribe /active_record/ do |*args|
  # do something
end
Plugins e gems não
precisam hackear o
  código do Rails
Menos hacks, melhor
manutenção e ecossistema
      OMG! Isso é incrível!
#5
Nova API do ActionMailer
É como se fosse a API do
     controller...
class Notifier < ActionMailer::Base
  default :from => "system@example.com"

  def signup_notification(recipient)
    @account = recipient
    attachments['image.jpg'] = File.read("image.jpg")
    mail(:to => recipient.email) do |format|
      format.html
      format.text
    end
  end
end
#1
             Class level defaults
class Notifier < ActionMailer::Base
  default :from => "system@example.com"

  def signup_notification(recipient)
    @account = recipient
    attachments['image.jpg'] = File.read("image.jpg")
    mail(:to => recipient.email) do |format|
      format.html
      format.text
    end
  end
end
#2
           Variáveis de instância
class Notifier < ActionMailer::Base
  default :from => "system@example.com"

  def signup_notification(recipient)
    @account = recipient
    attachments['image.jpg'] = File.read("image.jpg")
    mail(:to => recipient.email) do |format|
      format.html
      format.text
    end
  end
end
#3
        Anexos são como cookies
class Notifier < ActionMailer::Base
  default :from => "system@example.com"

  def signup_notification(recipient)
    @account = recipient
    attachments['image.jpg'] = File.read("image.jpg")
    mail(:to => recipient.email) do |format|
      format.html
      format.text
    end
  end
end
#4
   mail funciona como respond_to
class Notifier < ActionMailer::Base
  default :from => "system@example.com"

  def signup_notification(recipient)
    @account = recipient
    attachments['image.jpg'] = File.read("image.jpg")
    mail(:to => recipient.email) do |format|
      format.html
      format.text
    end
  end
end
Simples e mais poderoso
      OMG! Isso é incrível!
#6
ActiveModel
Quase todas as
aplicações precisam de
um modelo que tenham
que se comportar como
     ActiveRecord
Formulário de Contato
class ContactForm
  include ActiveModel::Conversion
  extend ActiveModel::Naming
  extend ActiveModel::Translation
  include ActiveModel::Validations

  attr_accessor :name, :email, :message

  def deliver
    valid? && Notifier.contact(self).deliver
  end

  def persisted?
    false
  end
end
ActiveModel desempenha
  um papel essencial no
      agnosticismo
User.model_name
 user.persisted?
   user.valid?
   user.errors
   user.to_key
 user.to_param
Liberdade de escolha
    OMG! Isso é incrível!
#7
Rails::Generators
Scaffold é mais que uma
ferramenta de aprendizado
Agora ele adapta ao seu
       work ow
Rails 2.3

   script/generate
dm_rspec_scaffold User
Rails 2.3

   script/generate
dm_rspec_scaffold User
   OMG! Isso NÃO é incrível!
E se eu quisesse usar
Datamapper, Rspec e
        Haml?
Rails 3

config.generators do |g|
  g.orm :datamapper
  g.template_engine :haml
  g.test_framework :rspec, :views => false
  g.fixture_replacement :factory_girl,
                         :dir => "spec/factories"
end
Rails 3


rails g scaffold User
   OMG! Isso é incrível!
Vocês podem customizar
cada pedaço do scaffold
Rails 3

RAILS_ROOT/lib/templates/erb/scaffold/index.html.erb
RAILS_ROOT/lib/templates/erb/scaffold/show.html.erb
RAILS_ROOT/lib/templates/erb/scaffold/new.html.erb
RAILS_ROOT/lib/templates/erb/scaffold/edit.html.erb
O scaffold muda como a
  sua aplicação muda!
Customização!
 OMG! Isso é incrível!
?!
    @plataformatec
blog.plataformatec.com

Mais conteúdo relacionado

Mais procurados

13 java beans
13 java beans13 java beans
13 java beans
snopteck
 
JSP Syntax_1
JSP Syntax_1JSP Syntax_1
JSP Syntax_1
brecke
 
Admin High Availability
Admin High AvailabilityAdmin High Availability
Admin High Availability
rsnarayanan
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
RORLAB
 

Mais procurados (19)

Sel study notes
Sel study notesSel study notes
Sel study notes
 
13 java beans
13 java beans13 java beans
13 java beans
 
WebGUI Developers Workshop
WebGUI Developers WorkshopWebGUI Developers Workshop
WebGUI Developers Workshop
 
JSP Syntax_1
JSP Syntax_1JSP Syntax_1
JSP Syntax_1
 
13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS 13th Sep, Drupal 7 advanced training by TCS
13th Sep, Drupal 7 advanced training by TCS
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
Rails 3 Beautiful Code
Rails 3 Beautiful CodeRails 3 Beautiful Code
Rails 3 Beautiful Code
 
Silex Cheat Sheet
Silex Cheat SheetSilex Cheat Sheet
Silex Cheat Sheet
 
Admin High Availability
Admin High AvailabilityAdmin High Availability
Admin High Availability
 
Unit iv
Unit ivUnit iv
Unit iv
 
Building and managing java projects with maven part-III
Building and managing java projects with maven part-IIIBuilding and managing java projects with maven part-III
Building and managing java projects with maven part-III
 
Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2Layouts and Rendering in Rails, Season 2
Layouts and Rendering in Rails, Season 2
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
Java beans
Java beansJava beans
Java beans
 
Beans presentation
Beans presentationBeans presentation
Beans presentation
 
Javabeans
JavabeansJavabeans
Javabeans
 
Maven II
Maven IIMaven II
Maven II
 
Jsp Notes
Jsp NotesJsp Notes
Jsp Notes
 
Drupal 7 as a rad tool
Drupal 7 as a rad toolDrupal 7 as a rad tool
Drupal 7 as a rad tool
 

Destaque (9)

Joy to the World Remix
Joy to the World RemixJoy to the World Remix
Joy to the World Remix
 
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
O que há de novo no Rails 3 - Ruby on Rails no Mundo Real - 23may2010
 
Slides of old cumbernauld
Slides of old cumbernauldSlides of old cumbernauld
Slides of old cumbernauld
 
Rails Contributors
Rails ContributorsRails Contributors
Rails Contributors
 
Presentation1
Presentation1Presentation1
Presentation1
 
Rails 2.3, 3.0 and 3.1 - RubyConfBR - 26oct2010
Rails 2.3, 3.0 and 3.1 - RubyConfBR - 26oct2010Rails 2.3, 3.0 and 3.1 - RubyConfBR - 26oct2010
Rails 2.3, 3.0 and 3.1 - RubyConfBR - 26oct2010
 
As reais razões do porque eu devo ser Ágil - Agile Tour São Paulo
As reais razões do porque eu devo ser Ágil - Agile Tour São PauloAs reais razões do porque eu devo ser Ágil - Agile Tour São Paulo
As reais razões do porque eu devo ser Ágil - Agile Tour São Paulo
 
Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010Código Saudável => Programador Feliz - Rs on Rails 2010
Código Saudável => Programador Feliz - Rs on Rails 2010
 
Do your own hacking evening - RubyConf UR
Do your own hacking evening - RubyConf URDo your own hacking evening - RubyConf UR
Do your own hacking evening - RubyConf UR
 

Semelhante a Rails 3 - The Developers Conference - 21aug2010

Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
Lucas Renan
 

Semelhante a Rails 3 - The Developers Conference - 21aug2010 (20)

The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Rest And Rails
Rest And RailsRest And Rails
Rest And Rails
 
Caldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW WorkshopCaldera Learn - LoopConf WP API + Angular FTW Workshop
Caldera Learn - LoopConf WP API + Angular FTW Workshop
 
Introduction à Ruby
Introduction à RubyIntroduction à Ruby
Introduction à Ruby
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Rails2 Pr
Rails2 PrRails2 Pr
Rails2 Pr
 
Rails 2.0 Presentation
Rails 2.0 PresentationRails 2.0 Presentation
Rails 2.0 Presentation
 
Be happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP ItuBe happy with Ruby on Rails - CEUNSP Itu
Be happy with Ruby on Rails - CEUNSP Itu
 
Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11Ruby on Rails at PROMPT ISEL '11
Ruby on Rails at PROMPT ISEL '11
 
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...Laravel development (Laravel History, Environment Setup & Laravel Installatio...
Laravel development (Laravel History, Environment Setup & Laravel Installatio...
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
Spring5 New Features
Spring5 New FeaturesSpring5 New Features
Spring5 New Features
 
Routing 1, Season 1
Routing 1, Season 1Routing 1, Season 1
Routing 1, Season 1
 
BEAR (Suday) design
BEAR (Suday) designBEAR (Suday) design
BEAR (Suday) design
 
More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Rails vs Web2py
Rails vs Web2pyRails vs Web2py
Rails vs Web2py
 
WordPress REST API hacking
WordPress REST API hackingWordPress REST API hacking
WordPress REST API hacking
 
Supa fast Ruby + Rails
Supa fast Ruby + RailsSupa fast Ruby + Rails
Supa fast Ruby + Rails
 

Mais de Plataformatec

The Plafatorma Way - Oxente Rails - 05aug2010
The Plafatorma Way - Oxente Rails - 05aug2010The Plafatorma Way - Oxente Rails - 05aug2010
The Plafatorma Way - Oxente Rails - 05aug2010
Plataformatec
 

Mais de Plataformatec (11)

Product Owner - Simples como dizem? - Agile Tour 2011
Product Owner - Simples como dizem? - Agile Tour 2011Product Owner - Simples como dizem? - Agile Tour 2011
Product Owner - Simples como dizem? - Agile Tour 2011
 
Writing your own programming language to understand Ruby better - Euruko 2011
Writing your own programming language to understand Ruby better - Euruko 2011Writing your own programming language to understand Ruby better - Euruko 2011
Writing your own programming language to understand Ruby better - Euruko 2011
 
Railties - Ruby Masters Conf - 26Feb2011
Railties - Ruby Masters Conf - 26Feb2011Railties - Ruby Masters Conf - 26Feb2011
Railties - Ruby Masters Conf - 26Feb2011
 
CRUDing Open Source - WhyDay - 19aug2010
CRUDing Open Source - WhyDay - 19aug2010CRUDing Open Source - WhyDay - 19aug2010
CRUDing Open Source - WhyDay - 19aug2010
 
Rails 3 - RS on Rails - 21aug2010
Rails 3 - RS on Rails - 21aug2010Rails 3 - RS on Rails - 21aug2010
Rails 3 - RS on Rails - 21aug2010
 
Project Rescue - Oxente Rails - 05aug2010
Project Rescue - Oxente Rails - 05aug2010Project Rescue - Oxente Rails - 05aug2010
Project Rescue - Oxente Rails - 05aug2010
 
The Plafatorma Way - Oxente Rails - 05aug2010
The Plafatorma Way - Oxente Rails - 05aug2010The Plafatorma Way - Oxente Rails - 05aug2010
The Plafatorma Way - Oxente Rails - 05aug2010
 
DSL or NoDSL - Euruko - 29may2010
DSL or NoDSL - Euruko - 29may2010DSL or NoDSL - Euruko - 29may2010
DSL or NoDSL - Euruko - 29may2010
 
Classificação de textos - Dev in Sampa - 28nov2009
Classificação de textos - Dev in Sampa - 28nov2009Classificação de textos - Dev in Sampa - 28nov2009
Classificação de textos - Dev in Sampa - 28nov2009
 
Devise - RSLA - 13oct2009
Devise - RSLA - 13oct2009Devise - RSLA - 13oct2009
Devise - RSLA - 13oct2009
 
Thor - RSLA - 13oct2009
Thor - RSLA - 13oct2009Thor - RSLA - 13oct2009
Thor - RSLA - 13oct2009
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 

Rails 3 - The Developers Conference - 21aug2010

  • 4.
  • 7.
  • 9. Rails 3 OMG! Isso é incrível!
  • 13. Mas vocês já ouviram sobre isso...
  • 14. Como Rails 3 mudará o modo que desenvolvemos aplicações?
  • 16. “can't activate activesupport (= 2.3.4, runtime), already activated activesupport-2.3.5 (Gem::Exception)”
  • 18. } Rubygems #1 carregará a require “activesupport” última versão: 2.3.5
  • 19. } Rubygems #1 carregará a require “activesupport” última versão: 2.3.5 #2 gem “activesupport”, “2.3.4”
  • 20. Boom! OMG! Isso NÃO é incrível!
  • 21. # Gem le source 'http://gemcutter.org' gem 'rails', ' 3.0.0 ' gem 'sqlite3-ruby', :require => 'sqlite3' gem 'ruby-debug'
  • 22. Bundler resolve dependências e faz um “lock” do seu load path
  • 23. Bundler resolve dependências e faz um “lock” do seu load path
  • 24. Bundler resolve dependências e faz um “lock” do seu load path
  • 25. } #1 activesupport-2.2.2 activesupport-2.3.4 Filesystem activesupport-2.3.5
  • 26. } #1 activesupport-2.2.2 activesupport-2.3.4 Filesystem activesupport-2.3.5 } #2 gem “activesupport”, “2.3.4” Gemfile
  • 27. } #1 activesupport-2.2.2 activesupport-2.3.4 Filesystem activesupport-2.3.5 } #2 gem “activesupport”, “2.3.4” Gemfile } #3 activesupport-2.3.4 $LOAD_PATH
  • 28. Bundler garante que todos no mesmo projeto usam as mesmas dependências
  • 29. Gerenciamento de dependências OMG! Isso é incrível!
  • 31. Rails 2.3 def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end
  • 32. Rails 3 respond_to :html, :xml def index @users = User.all respond_with(@users) end
  • 33. Rails 3 respond_to :html, :xml def index @users = User.all Formato de respond_with(@users) navegação end
  • 34. Rails 3 respond_to :html, :xml def index Formato @users = User.all de API respond_with(@users) end
  • 35. Navegação API GET POST PUT DELETE
  • 36. Navegação API GET POST PUT DELETE
  • 37. Navegação API GET POST PUT DELETE
  • 38. def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end
  • 39. Navegação API GET render template POST PUT DELETE
  • 40. def index @users = User.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @users } end end
  • 41. Navegação API render GET render template resources.to_format POST PUT DELETE
  • 42. def create @user = User.new(params[:user]) respond_to do |format| if @user.save format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end
  • 43. Navegação API render GET render template resources.to_format Success POST Failure PUT DELETE
  • 44. if @user.save format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user }
  • 45. Navegação API render GET render template resources.to_format Success redirect_to resource POST Failure PUT DELETE
  • 46. if @user.save format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user }
  • 47. Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST Failure PUT DELETE
  • 48. else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity }
  • 49. Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST Failure render :new render resource.errors PUT DELETE
  • 50. Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST Failure render :new render resource.errors Success redirect_to resource head :ok PUT Failure render :edit render resource.errors DELETE redirect_to collection head :ok
  • 51. Três variáveis Verbo HTTP Estado do recurso Formato da requisição
  • 54. respond_with(@user) ActionController::Responder Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST render Failure render :new resource.errors Success redirect_to resource head :ok PUT render Failure render :edit resource.errors redirect_to DELETE head :ok collection
  • 55. respond_with(@user) ActionController::Responder tabela em código Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST render Failure render :new resource.errors Success redirect_to resource head :ok PUT render Failure render :edit resource.errors redirect_to DELETE head :ok collection
  • 56. def create @user = User.new(params[:user]) respond_to do |format| if @user.save format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.xml { render :xml => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.xml { render :xml => @user.errors, :status => :unprocessable_entity } end end end
  • 57. def create @user = User.new(params[:user]) flash[:user] = 'User was successfully created.' if @user.save respond_with(@user) end
  • 58. Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST Failure render :new render resource.errors Success redirect_to resource head :ok PUT Failure render :edit render resource.errors DELETE redirect_to collection head :ok
  • 59. Navegação API render GET render template resources.to_format render Success redirect_to resource resource.to_format POST Failure render :new render resource.errors Success redirect_to resource head :ok PUT Failure render :edit render resource.errors DELETE redirect_to collection head :ok
  • 60. Navegação API render GET render template resources.to_format render Success redirect_to collection resource.to_format POST Failure render :new render resource.errors Success redirect_to collection head :ok PUT Failure render :edit render resource.errors DELETE redirect_to collection head :ok
  • 61. Rails 2.3 a) Senta e chora b) Mata o cliente
  • 62. Rails 3 a) Senta e chora b) Mata o cliente c) Crie o seu responder
  • 63. DRY OMG! Isso é incrível!
  • 65. Rails 2.3 cars = Car.all(:conditions => { :color => 'black'}) expensive_cars = Car.all(:conditions => { :colour => 'black'}, :order => 'cars.price DESC', :limit => 10)
  • 66. Rails 3 cars = Car.where(:color => 'black') expensive_cars = cars. order('cars.price DESC').limit(10)
  • 67. Rails 3 # controller @cars = Car.where(:color => 'black') # view <% cache do %> <% @cars.each do |car| %> <%= car.name %> <% end %> <% end %>
  • 68. Rails 3 Não acessa o banco de dados # controller @cars = Car.where(:color => 'black') # view <% cache do %> <% @cars.each do |car| %> <%= car.name %> <% end %> <% end %>
  • 69. Rails 3 Não acessa o banco de dados # controller @cars = Car.where(:color => 'black') Acessa o # view banco de dados <% cache do %> <% @cars.each do |car| %> <%= car.name %> <% end %> <% end %>
  • 70. Melhor e mais rápido! OMG! Isso é incrível!
  • 72. É o “Facebook news feed” da sua aplicação
  • 73. ActiveSupport::Notifications. instrument "active_record.sql" do # query the database adapter end
  • 74. ActiveSupport::Notifications. subscribe /active_record/ do |*args| # do something end
  • 75. Plugins e gems não precisam hackear o código do Rails
  • 76. Menos hacks, melhor manutenção e ecossistema OMG! Isso é incrível!
  • 77. #5 Nova API do ActionMailer
  • 78. É como se fosse a API do controller...
  • 79. class Notifier < ActionMailer::Base default :from => "system@example.com" def signup_notification(recipient) @account = recipient attachments['image.jpg'] = File.read("image.jpg") mail(:to => recipient.email) do |format| format.html format.text end end end
  • 80. #1 Class level defaults class Notifier < ActionMailer::Base default :from => "system@example.com" def signup_notification(recipient) @account = recipient attachments['image.jpg'] = File.read("image.jpg") mail(:to => recipient.email) do |format| format.html format.text end end end
  • 81. #2 Variáveis de instância class Notifier < ActionMailer::Base default :from => "system@example.com" def signup_notification(recipient) @account = recipient attachments['image.jpg'] = File.read("image.jpg") mail(:to => recipient.email) do |format| format.html format.text end end end
  • 82. #3 Anexos são como cookies class Notifier < ActionMailer::Base default :from => "system@example.com" def signup_notification(recipient) @account = recipient attachments['image.jpg'] = File.read("image.jpg") mail(:to => recipient.email) do |format| format.html format.text end end end
  • 83. #4 mail funciona como respond_to class Notifier < ActionMailer::Base default :from => "system@example.com" def signup_notification(recipient) @account = recipient attachments['image.jpg'] = File.read("image.jpg") mail(:to => recipient.email) do |format| format.html format.text end end end
  • 84. Simples e mais poderoso OMG! Isso é incrível!
  • 86. Quase todas as aplicações precisam de um modelo que tenham que se comportar como ActiveRecord
  • 88. class ContactForm include ActiveModel::Conversion extend ActiveModel::Naming extend ActiveModel::Translation include ActiveModel::Validations attr_accessor :name, :email, :message def deliver valid? && Notifier.contact(self).deliver end def persisted? false end end
  • 89. ActiveModel desempenha um papel essencial no agnosticismo
  • 90. User.model_name user.persisted? user.valid? user.errors user.to_key user.to_param
  • 91. Liberdade de escolha OMG! Isso é incrível!
  • 93. Scaffold é mais que uma ferramenta de aprendizado
  • 94. Agora ele adapta ao seu work ow
  • 95. Rails 2.3 script/generate dm_rspec_scaffold User
  • 96. Rails 2.3 script/generate dm_rspec_scaffold User OMG! Isso NÃO é incrível!
  • 97. E se eu quisesse usar Datamapper, Rspec e Haml?
  • 98. Rails 3 config.generators do |g| g.orm :datamapper g.template_engine :haml g.test_framework :rspec, :views => false g.fixture_replacement :factory_girl, :dir => "spec/factories" end
  • 99. Rails 3 rails g scaffold User OMG! Isso é incrível!
  • 100. Vocês podem customizar cada pedaço do scaffold
  • 102. O scaffold muda como a sua aplicação muda!
  • 103. Customização! OMG! Isso é incrível!
  • 104. ?! @plataformatec blog.plataformatec.com

Notas do Editor