SlideShare uma empresa Scribd logo
1 de 28
Baixar para ler offline
Les nouveautés de Rails 3
     Simon COURTOIS
   Expert en Open-Source
   scourtois@linagora.com




             1              WWW.LINAGORA.COM
La commande rails




                      Rails 2             Rails 3


                rails myapp          rails new myapp


                ./script/generate    rails g

                ./script/console     rails c

                ./script/server      rails s

                ./script/dbconsole   rails db




2 /25
La commande rails




        •   --skip-activerecord, -O    .gitignore

        •   --skip-test-unit, -T
                                      .bundle
        •   --skip-prototype, -J      db/*.sqlite3
                                      log/*.log
                                      tmp/
        •   --skip-git, -G   ???




3 /25
Bundler




        Rails 2
 Rails::Initializer.run do |config|
   ... config.gem 'haml' config.gem 'coderay',
 :version => '~>0.9.7' ...end

                                              config/environment.rb




        Rails 3
 source 'http://rubygems.org'gem 'rails', '3.0.6'gem 'haml'gem
 'coderay', '~> 0.9.7'group :development, :test do gem
 'cucumber-rails'
 end

                                                           Gemfile
                                                                      bundle install




4 /25
ActiveRelation




                 Rails 2
         @articles = Article.find(:all, :conditions => {:published => true})


                 ¬   requête immédiate
                 ¬   retourne un tableau d’articles


                 Rails 3
         @articles = Article.where(:published => true)


                 ¬   pas de requête
                 ¬   retourne un objet ActiveRecord::Relation




5 /25
ActiveRelation




             @articles = Article.where(:published => true)

             if params[:order]
               @articles = @articles.order(params[:order])
             end

             @articles.each do |article|
               ...
             end




                                requête effectuée


6 /25
ActiveRelation




             @articles = Article.where(:published => true)


             @articles = @articles.order(params[:order])


             @articles.each do |article|
               ...
             end




7 /25
ActiveRelation




             @articles = Article.where(:published => true).order(params[:order])




             @articles.each do |article|
               ...
             end




8 /25
ActiveRelation




                 articles = Article.order(params[:order])

                 @published   = articles.where(:published => true)
                 @unpublished = articles.where(:published => false)




9 /25
ActiveRelation




                  @published   = articles.published
                  @unpublished = articles.unpublished



                  class Article < ActiveRecord::Base
                    named_scope :published,   :conditions => {:published => true}
        Rails 2     named_scope :unpublished, :conditions => {:published => false}
                  end



                  class Article < ActiveRecord::Base
                    scope :published,   where(:published => true)
        Rails 3     scope :unpublished, where(:published => false)
                  end




10/25
ActiveRelation




           where(:conditions)    all
           having(:conditions)   first
           select                last
           group
           order
           limit
           offset
           joins
           includes(:include)
           lock
           readonly
           from



11/25
ActiveRelation




             Rails 2
        Article.find(:all, :conditions => {:author => “Bob”}, :includes => :comments,
                     :order => “title”, :limit => 10)




             Rails 3
        Article.where(:author => “Bob”).includes(:comments).order(“title”).limit(10).all




12/25
ActiveController


                     Rails 2                                      Rails 3
class ArticlesController < ApplicationController   class ArticlesController < Applic...
  def index                                          respond_to :html, :xml
    @users = User.all
                                                    def index
   respond_to do |format|                             @users = User.all
     format.html                                      respond_with(@users)
     format.xml { render :xml => @users.to_xml }    end
   end
 end                                                 def show
                                                       @user = User.find(params[:id])
 def show                                              respond_with(@user)
   @user = User.find(params[:id])                    end
                                                   end
    respond_to do |format|
      format.html
      format.xml { render :xml => @user }
    end
  end
end



flash[:notice] = “Article created”                 redirect_to @article,
redirect_to @article                                           :notice => “Article created”




13/25
Le routing




                    Rails 2                                       Rails 3
ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
  map.resources :articles                           resources :articles
end                                               end




14/25
Le routing




                     Rails 2                                        Rails 3
ActionController::Routing::Routes.draw do |map|     Myapp::Application.routes.draw do |map|
  map.resources :articles,                            resources :articles do
            :member     => { :preview => :post },       member do
            :collection => { :archived => :get }          post :preview
end                                                     end

                                                        collection do
                                                          get :archived
                                                        end
                                                      end
                                                    end



                                                    Myapp::Application.routes.draw do |map|
                                                      resources :articles do
                                                       post :preview, :on => :member
                                                       get :archived, :on => :collection
                                                      end
                                                    end




15/25
Le routing




                     Rails 2                                       Rails 3
 ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
   map.resources :articles do |article|              resources :articles do
     article.resources :comments                       resources :comments
   end                                               end
 end                                               end



 ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
   map.connect “login”,                              match “login” => “session#new”
               :controller => “session”,           end
               :action     => “new”
 end




16/25
Le routing




                      Rails 2                                           Rails 3
  ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
    map.login “login”,                                match “login” => “session#new”, :as => :login
              :controller => “session”,             end
              :action     => “new”
  end




  ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
    map.root :controller => “articles”,               root :to => “users#index”
             :action     => “index”                 end
  end




  ActionController::Routing::Routes.draw do |map|   Myapp::Application.routes.draw do |map|
    map.connect “:controller/:action/:id”             match “:controller(/:action(/:id(.:format)))”
    map.connect “:controller/:action/:id.:format”   end
  end




17/25
Le routing




        Rails 2
   ActionController::Routing::Routes.draw do |map|
     map.connect ‘/articles/:year/:month/:day’, :controller => “articles”, :action => “index”
     map.connect ‘/articles/:year/:month’,      :controller => “articles”, :action => “index”
     map.connect ‘/articles/:year’,             :controller => “articles”, :action => “index”
   end




        Rails 3
   Myapp::Application.routes.draw do |map|
     match “/articles(/:year(/:month(/:day)))” => “articles#index”
   end




18/25
Le routing




         Rails 2
    ActionController::Routing::Routes.draw do |map|
      map.connect ‘/articles/:year’, :controller => “articles”, :action => “index”,
                                     :conditions => { :method => :get }
    end




         Rails 3
    Myapp::Application.routes.draw do |map|
      match “/articles/:year” => “articles#index”, :via => :get
    end



    Myapp::Application.routes.draw do |map|
      get “/articles/:year” => “articles#index”
    end




19/25
Le routing




                                            Rails 3
        Myapp::Application.routes.draw do |map|
          match “signin”,   :to => redirect(“/login”)
          match “linagora”, :to => redirect(“http://www.linagora.com”)
        end




        Myapp::Application.routes.draw do |map|
          get “hello”    => proc { |env| [200, {}, “Hello World !”] }
          get “rack_app” => MyCoolRackApp
        end




                      RAILS_ROOT/lib/my_cool_rack_app.rb




20/25
XSS et Unobstrusive JS




                   Rails 2                                                  Rails 3
 <%= @article.title %>   # Non sécurisé             <%= @article.title %>      # Sécurisé

 <%=h @article.title %> # Sécurisé                  <%=raw @article.title %> # Non sécurisé




 <%= link_to_remote “Show”, :url => @article %>     <%= link_to “Show”, :remote => true %>


<a href=”#” onclick=”new                            <a href=”/articles/1” data-remote=”true”>Show</a>
Ajax.Request(‘/articles/1’,
{asynchronous:true,evalScripts:true,parameters:‘a
uthenticity_token=’+encodeURIComponent(‘A9s...3cf
’)}); return false;”>Show</a>


<% remote_form_for(@article) do |f| %>              <%= form_for(@article, :remote => true) do |f| %>


<form action=”/articles” class=”new_post”           <form action=”/articles” class=”new_post”
id=”new_post” method=”post” onSubmit=”new           id=”new_post” method=”post” data-remote=”true”>
Ajax.Request(‘/articles’,
{asynchronous:true,evalScripts:true,parameters:Fo
rm.serialize(this)}); return false;”>

  21/25
XSS et Unobstrusive JS




                         <%= link_to “Delete”, @article, :method => :delete %>




                     <a href="#" title="Delete" onclick="var f =
                     document.createElement('form'); f.style.display = 'none';
                     this.parentNode.appendChild(f); f.method = 'POST'; f.action =
        Rails 2      this.href;var s = document.createElement('input');
                     s.setAttribute('type', 'hidden'); s.setAttribute('name',
                     'authenticity_token'); s.setAttribute('value', 'XXX...XXX');
                     f.appendChild(s);f.submit(); return false;">Delete</a>




        Rails 3      <a href=”/articles/1” data-method=”delete” rel=”nofollow”>Delete</a>




22/25
XSS et Unobstrusive JS




                         <%= link_to “Delete”, @article, :method => :delete,
                                     :confirm => “Are you sure ?” %>




                     <a href="#" title="Delete" onclick="if (confirm(“Are you sure ?”))
                     {var f = document.createElement('form'); f.style.display = 'none';
                     this.parentNode.appendChild(f); f.method = 'POST'; f.action =
        Rails 2      this.href;var s = document.createElement('input');
                     s.setAttribute('type', 'hidden'); s.setAttribute('name',
                     'authenticity_token'); s.setAttribute('value', 'XXX...XXX');
                     f.appendChild(s);f.submit();} return false;">Delete</a>




        Rails 3      <a href=”/articles/1” data-method=”delete”
                        data-confirm=”Are you sure ?” rel=”nofollow”>Delete</a>




23/25
Prochaine étape




  Rails 3.1

        •   jQuery

        •   CoffeeScript

        •   Sass




24/25
Prochaine étape
                           number = 42 if true

                           square = (x) -> x * x

                           alert "Hello" if number?

                           list = [1, 2, 3, 4]


  Rails 3.1
                           squares = (square num for num in list)



                           var number, square, list, squares, num;
        •   jQuery         if (true) {
                             number = 42;
                           }
        •   CoffeeScript   square = function(x) {
                             return x * x;
                           };
                           if (typeof number !== "undefined" && number !== null) {
        •   Sass           }
                             alert("Hello");

                           squares = (function() {
                             var _i, _len, _results;
                             _results = [];
                             for (_i = 0, _len = list.length; _i < _len; _i++) {
                               num = list[_i];
                               _results.push(square(num));
                             }
                             return _results;
                           })();

25/25
Prochaine étape



                           table.hl
                             margin: 2em 0
                             td.ln
                               text-align: right


  Rails 3.1
                           li
                             font:
                               family: serif
                               weight: bold

            jQuery
                               size:   1.2em
        •

        •   CoffeeScript   table.hl {
                             margin: 2em 0;
                           }
                           table.hl td.ln {
        •   Sass           }
                             text-align: right;


                           li {
                             font-family: serif;
                             font-weight: bold;
                             font-size:   1.2em;
                           }




26/25
Prochaine étape



                           table.hl
                             margin: 2em 0
                             td.ln
                               text-align: right


  Rails 3.1
                           li
                             font:
                               family: serif
                               weight: bold

            jQuery
                               size:   1.2em
        •

        •   CoffeeScript   table.hl {
                             margin: 2em 0;
                           }
                           table.hl td.ln {
        •   Sass           }
                             text-align: right;


                           li {
                             font-family: serif;
                             font-weight: bold;
                             font-size:   1.2em;
                           }




27/25
Merci de votre attention

                                               Cont act :
                               LINAGORA - Siège social
                                 80, rue Roque de Fillol
                                         92800 PUTEAUX
                                                FRANCE
                      Tél. : 0 810 251 251 (t arif local)
                           Fax : +33 (0)1 46 96 63 64
                               Mail : info@linagora.com
                               Web : www.linagora.com


           28          WWW.LINAGORA.COM

Mais conteúdo relacionado

Mais procurados

Your first sinatra app
Your first sinatra appYour first sinatra app
Your first sinatra app
Rubyc Slides
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3
Clinton Dreisbach
 

Mais procurados (20)

More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Curing Webpack Cancer
Curing Webpack CancerCuring Webpack Cancer
Curing Webpack Cancer
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Rails web api 开发
Rails web api 开发Rails web api 开发
Rails web api 开发
 
Your first sinatra app
Your first sinatra appYour first sinatra app
Your first sinatra app
 
The road to Ember.js 2.0
The road to Ember.js 2.0The road to Ember.js 2.0
The road to Ember.js 2.0
 
Intro to Rails
Intro to Rails Intro to Rails
Intro to Rails
 
Getting Started-with-Laravel
Getting Started-with-LaravelGetting Started-with-Laravel
Getting Started-with-Laravel
 
Create a new project in ROR
Create a new project in RORCreate a new project in ROR
Create a new project in ROR
 
Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2Laravel Beginners Tutorial 2
Laravel Beginners Tutorial 2
 
Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3Migrating Legacy Rails Apps to Rails 3
Migrating Legacy Rails Apps to Rails 3
 
The Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane MaldiniThe Value of Reactive Design - Stéphane Maldini
The Value of Reactive Design - Stéphane Maldini
 
Pourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirentPourquoi ruby et rails déchirent
Pourquoi ruby et rails déchirent
 
1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)1時間で作るマッシュアップサービス(関西版)
1時間で作るマッシュアップサービス(関西版)
 
Laravel 5 In Depth
Laravel 5 In DepthLaravel 5 In Depth
Laravel 5 In Depth
 
Laravel for Web Artisans
Laravel for Web ArtisansLaravel for Web Artisans
Laravel for Web Artisans
 
Getting Started With Aura
Getting Started With AuraGetting Started With Aura
Getting Started With Aura
 
Creating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 ComponentsCreating your own framework on top of Symfony2 Components
Creating your own framework on top of Symfony2 Components
 
Intro to Rack
Intro to RackIntro to Rack
Intro to Rack
 
Containers & Dependency in Ember.js
Containers & Dependency in Ember.jsContainers & Dependency in Ember.js
Containers & Dependency in Ember.js
 

Destaque (9)

Michaela Assignment #2
Michaela Assignment #2Michaela Assignment #2
Michaela Assignment #2
 
Storytelling in languages
Storytelling in languagesStorytelling in languages
Storytelling in languages
 
Augmenting Human Compassion: A Conceptual Framework
Augmenting Human Compassion:  A Conceptual FrameworkAugmenting Human Compassion:  A Conceptual Framework
Augmenting Human Compassion: A Conceptual Framework
 
Live@edu ilm2007
Live@edu ilm2007Live@edu ilm2007
Live@edu ilm2007
 
Economics 3.2
Economics 3.2Economics 3.2
Economics 3.2
 
The Effects of Chronic Multitasking on Analytical Writing
The Effects of Chronic Multitasking on Analytical WritingThe Effects of Chronic Multitasking on Analytical Writing
The Effects of Chronic Multitasking on Analytical Writing
 
LemonLDAP::NG, un WebSSO libre
LemonLDAP::NG, un WebSSO libreLemonLDAP::NG, un WebSSO libre
LemonLDAP::NG, un WebSSO libre
 
Industrialisez le développement et la maintenance de vos sites avec Drupal
Industrialisez le développement et la maintenance de vos sites avec DrupalIndustrialisez le développement et la maintenance de vos sites avec Drupal
Industrialisez le développement et la maintenance de vos sites avec Drupal
 
CapDémat Evolution plateforme de GRU pour collectivités
CapDémat Evolution plateforme de GRU pour collectivitésCapDémat Evolution plateforme de GRU pour collectivités
CapDémat Evolution plateforme de GRU pour collectivités
 

Semelhante a Les nouveautés de Rails 3

Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編
Masakuni Kato
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developers
alkeshv
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amf
railsconf
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
Juan Maiz
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Rails Routing and URL design
Rails Routing and URL designRails Routing and URL design
Rails Routing and URL design
hiq5
 

Semelhante a Les nouveautés de Rails 3 (20)

Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編浜松Rails3道場 其の四 View編
浜松Rails3道場 其の四 View編
 
Rails3 for Rails2 developers
Rails3 for Rails2 developersRails3 for Rails2 developers
Rails3 for Rails2 developers
 
Integrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby AmfIntegrating Flex And Rails With Ruby Amf
Integrating Flex And Rails With Ruby Amf
 
Flex With Rubyamf
Flex With RubyamfFlex With Rubyamf
Flex With Rubyamf
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful Rails
 
Advanced RESTful Rails
Advanced RESTful RailsAdvanced RESTful Rails
Advanced RESTful Rails
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Intro to Rails 4
Intro to Rails 4Intro to Rails 4
Intro to Rails 4
 
Introduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman OrtegaIntroduction to Rails - presented by Arman Ortega
Introduction to Rails - presented by Arman Ortega
 
Play vs Rails
Play vs RailsPlay vs Rails
Play vs Rails
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011TorqueBox - Ruby Hoedown 2011
TorqueBox - Ruby Hoedown 2011
 
Merb
MerbMerb
Merb
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
 
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
 
Rails Routing and URL design
Rails Routing and URL designRails Routing and URL design
Rails Routing and URL design
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 

Mais de LINAGORA

Présentation offre LINID
Présentation offre LINIDPrésentation offre LINID
Présentation offre LINID
LINAGORA
 

Mais de LINAGORA (20)

Personal branding : e-recrutement et réseaux sociaux professionnels
Personal branding : e-recrutement et réseaux sociaux professionnels Personal branding : e-recrutement et réseaux sociaux professionnels
Personal branding : e-recrutement et réseaux sociaux professionnels
 
Construisons ensemble le chatbot bancaire dedemain !
Construisons ensemble le chatbot bancaire dedemain !Construisons ensemble le chatbot bancaire dedemain !
Construisons ensemble le chatbot bancaire dedemain !
 
ChatBots et intelligence artificielle arrivent dans les banques
ChatBots et intelligence artificielle arrivent dans les banques ChatBots et intelligence artificielle arrivent dans les banques
ChatBots et intelligence artificielle arrivent dans les banques
 
Deep Learning in practice : Speech recognition and beyond - Meetup
Deep Learning in practice : Speech recognition and beyond - MeetupDeep Learning in practice : Speech recognition and beyond - Meetup
Deep Learning in practice : Speech recognition and beyond - Meetup
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Call a C API from Python becomes more enjoyable with CFFI
Call a C API from Python becomes more enjoyable with CFFICall a C API from Python becomes more enjoyable with CFFI
Call a C API from Python becomes more enjoyable with CFFI
 
[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)
[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)
[UDS] Cloud Computing "pour les nuls" (Exemple avec LinShare)
 
Angular v2 et plus : le futur du développement d'applications en entreprise
Angular v2 et plus : le futur du développement d'applications en entrepriseAngular v2 et plus : le futur du développement d'applications en entreprise
Angular v2 et plus : le futur du développement d'applications en entreprise
 
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORAComment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
Comment faire ses mappings ElasticSearch aux petits oignons ? - LINAGORA
 
Angular (v2 and up) - Morning to understand - Linagora
Angular (v2 and up) - Morning to understand - LinagoraAngular (v2 and up) - Morning to understand - Linagora
Angular (v2 and up) - Morning to understand - Linagora
 
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
Présentation du marché P2I UGAP « Support sur Logiciels Libres »Présentation du marché P2I UGAP « Support sur Logiciels Libres »
Présentation du marché P2I UGAP « Support sur Logiciels Libres »
 
Offre de demat d'Adullact projet
Offre de demat d'Adullact projet Offre de demat d'Adullact projet
Offre de demat d'Adullact projet
 
La dématérialisation du conseil minicipal
La dématérialisation du conseil minicipalLa dématérialisation du conseil minicipal
La dématérialisation du conseil minicipal
 
Open stack @ sierra wireless
Open stack @ sierra wirelessOpen stack @ sierra wireless
Open stack @ sierra wireless
 
OpenStack - open source au service du Cloud
OpenStack - open source au service du CloudOpenStack - open source au service du Cloud
OpenStack - open source au service du Cloud
 
Architecture d'annuaire hautement disponible avec OpenLDAP
Architecture d'annuaire hautement disponible avec OpenLDAPArchitecture d'annuaire hautement disponible avec OpenLDAP
Architecture d'annuaire hautement disponible avec OpenLDAP
 
Présentation offre LINID
Présentation offre LINIDPrésentation offre LINID
Présentation offre LINID
 
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
Matinée pour conmrendre consacrée à LinID.org, gestion, fédération et contrôl...
 
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
Matinée pour conmrendre consacrée à LinShare.org, application de partage de f...
 
Open Source Software Assurance by Linagora
Open Source Software Assurance by LinagoraOpen Source Software Assurance by Linagora
Open Source Software Assurance by Linagora
 

Último

Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
UXDXConf
 

Último (20)

WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptxWSO2CONMay2024OpenSourceConferenceDebrief.pptx
WSO2CONMay2024OpenSourceConferenceDebrief.pptx
 
ECS 2024 Teams Premium - Pretty Secure
ECS 2024   Teams Premium - Pretty SecureECS 2024   Teams Premium - Pretty Secure
ECS 2024 Teams Premium - Pretty Secure
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
Intro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджераIntro in Product Management - Коротко про професію продакт менеджера
Intro in Product Management - Коротко про професію продакт менеджера
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101AI presentation and introduction - Retrieval Augmented Generation RAG 101
AI presentation and introduction - Retrieval Augmented Generation RAG 101
 
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
TEST BANK For, Information Technology Project Management 9th Edition Kathy Sc...
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdfIntroduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
Introduction to FDO and How It works Applications _ Richard at FIDO Alliance.pdf
 
Powerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara LaskowskaPowerful Start- the Key to Project Success, Barbara Laskowska
Powerful Start- the Key to Project Success, Barbara Laskowska
 
Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
How we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdfHow we scaled to 80K users by doing nothing!.pdf
How we scaled to 80K users by doing nothing!.pdf
 
Structuring Teams and Portfolios for Success
Structuring Teams and Portfolios for SuccessStructuring Teams and Portfolios for Success
Structuring Teams and Portfolios for Success
 
A Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System StrategyA Business-Centric Approach to Design System Strategy
A Business-Centric Approach to Design System Strategy
 
What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024What's New in Teams Calling, Meetings and Devices April 2024
What's New in Teams Calling, Meetings and Devices April 2024
 
IESVE for Early Stage Design and Planning
IESVE for Early Stage Design and PlanningIESVE for Early Stage Design and Planning
IESVE for Early Stage Design and Planning
 
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdfLinux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
Linux Foundation Edge _ Overview of FDO Software Components _ Randy at Intel.pdf
 
Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024Enterprise Knowledge Graphs - Data Summit 2024
Enterprise Knowledge Graphs - Data Summit 2024
 

Les nouveautés de Rails 3

  • 1. Les nouveautés de Rails 3 Simon COURTOIS Expert en Open-Source scourtois@linagora.com 1 WWW.LINAGORA.COM
  • 2. La commande rails Rails 2 Rails 3 rails myapp rails new myapp ./script/generate rails g ./script/console rails c ./script/server rails s ./script/dbconsole rails db 2 /25
  • 3. La commande rails • --skip-activerecord, -O .gitignore • --skip-test-unit, -T .bundle • --skip-prototype, -J db/*.sqlite3 log/*.log tmp/ • --skip-git, -G ??? 3 /25
  • 4. Bundler Rails 2 Rails::Initializer.run do |config| ... config.gem 'haml' config.gem 'coderay', :version => '~>0.9.7' ...end config/environment.rb Rails 3 source 'http://rubygems.org'gem 'rails', '3.0.6'gem 'haml'gem 'coderay', '~> 0.9.7'group :development, :test do gem 'cucumber-rails' end Gemfile bundle install 4 /25
  • 5. ActiveRelation Rails 2 @articles = Article.find(:all, :conditions => {:published => true}) ¬ requête immédiate ¬ retourne un tableau d’articles Rails 3 @articles = Article.where(:published => true) ¬ pas de requête ¬ retourne un objet ActiveRecord::Relation 5 /25
  • 6. ActiveRelation @articles = Article.where(:published => true) if params[:order] @articles = @articles.order(params[:order]) end @articles.each do |article| ... end requête effectuée 6 /25
  • 7. ActiveRelation @articles = Article.where(:published => true) @articles = @articles.order(params[:order]) @articles.each do |article| ... end 7 /25
  • 8. ActiveRelation @articles = Article.where(:published => true).order(params[:order]) @articles.each do |article| ... end 8 /25
  • 9. ActiveRelation articles = Article.order(params[:order]) @published = articles.where(:published => true) @unpublished = articles.where(:published => false) 9 /25
  • 10. ActiveRelation @published = articles.published @unpublished = articles.unpublished class Article < ActiveRecord::Base named_scope :published, :conditions => {:published => true} Rails 2 named_scope :unpublished, :conditions => {:published => false} end class Article < ActiveRecord::Base scope :published, where(:published => true) Rails 3 scope :unpublished, where(:published => false) end 10/25
  • 11. ActiveRelation where(:conditions) all having(:conditions) first select last group order limit offset joins includes(:include) lock readonly from 11/25
  • 12. ActiveRelation Rails 2 Article.find(:all, :conditions => {:author => “Bob”}, :includes => :comments, :order => “title”, :limit => 10) Rails 3 Article.where(:author => “Bob”).includes(:comments).order(“title”).limit(10).all 12/25
  • 13. ActiveController Rails 2 Rails 3 class ArticlesController < ApplicationController class ArticlesController < Applic... def index respond_to :html, :xml @users = User.all def index respond_to do |format| @users = User.all format.html respond_with(@users) format.xml { render :xml => @users.to_xml } end end end def show @user = User.find(params[:id]) def show respond_with(@user) @user = User.find(params[:id]) end end respond_to do |format| format.html format.xml { render :xml => @user } end end end flash[:notice] = “Article created” redirect_to @article, redirect_to @article :notice => “Article created” 13/25
  • 14. Le routing Rails 2 Rails 3 ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.resources :articles resources :articles end end 14/25
  • 15. Le routing Rails 2 Rails 3 ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.resources :articles, resources :articles do :member => { :preview => :post }, member do :collection => { :archived => :get } post :preview end end collection do get :archived end end end Myapp::Application.routes.draw do |map| resources :articles do post :preview, :on => :member get :archived, :on => :collection end end 15/25
  • 16. Le routing Rails 2 Rails 3 ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.resources :articles do |article| resources :articles do article.resources :comments resources :comments end end end end ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.connect “login”, match “login” => “session#new” :controller => “session”, end :action => “new” end 16/25
  • 17. Le routing Rails 2 Rails 3 ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.login “login”, match “login” => “session#new”, :as => :login :controller => “session”, end :action => “new” end ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.root :controller => “articles”, root :to => “users#index” :action => “index” end end ActionController::Routing::Routes.draw do |map| Myapp::Application.routes.draw do |map| map.connect “:controller/:action/:id” match “:controller(/:action(/:id(.:format)))” map.connect “:controller/:action/:id.:format” end end 17/25
  • 18. Le routing Rails 2 ActionController::Routing::Routes.draw do |map| map.connect ‘/articles/:year/:month/:day’, :controller => “articles”, :action => “index” map.connect ‘/articles/:year/:month’, :controller => “articles”, :action => “index” map.connect ‘/articles/:year’, :controller => “articles”, :action => “index” end Rails 3 Myapp::Application.routes.draw do |map| match “/articles(/:year(/:month(/:day)))” => “articles#index” end 18/25
  • 19. Le routing Rails 2 ActionController::Routing::Routes.draw do |map| map.connect ‘/articles/:year’, :controller => “articles”, :action => “index”, :conditions => { :method => :get } end Rails 3 Myapp::Application.routes.draw do |map| match “/articles/:year” => “articles#index”, :via => :get end Myapp::Application.routes.draw do |map| get “/articles/:year” => “articles#index” end 19/25
  • 20. Le routing Rails 3 Myapp::Application.routes.draw do |map| match “signin”, :to => redirect(“/login”) match “linagora”, :to => redirect(“http://www.linagora.com”) end Myapp::Application.routes.draw do |map| get “hello” => proc { |env| [200, {}, “Hello World !”] } get “rack_app” => MyCoolRackApp end RAILS_ROOT/lib/my_cool_rack_app.rb 20/25
  • 21. XSS et Unobstrusive JS Rails 2 Rails 3 <%= @article.title %> # Non sécurisé <%= @article.title %> # Sécurisé <%=h @article.title %> # Sécurisé <%=raw @article.title %> # Non sécurisé <%= link_to_remote “Show”, :url => @article %> <%= link_to “Show”, :remote => true %> <a href=”#” onclick=”new <a href=”/articles/1” data-remote=”true”>Show</a> Ajax.Request(‘/articles/1’, {asynchronous:true,evalScripts:true,parameters:‘a uthenticity_token=’+encodeURIComponent(‘A9s...3cf ’)}); return false;”>Show</a> <% remote_form_for(@article) do |f| %> <%= form_for(@article, :remote => true) do |f| %> <form action=”/articles” class=”new_post” <form action=”/articles” class=”new_post” id=”new_post” method=”post” onSubmit=”new id=”new_post” method=”post” data-remote=”true”> Ajax.Request(‘/articles’, {asynchronous:true,evalScripts:true,parameters:Fo rm.serialize(this)}); return false;”> 21/25
  • 22. XSS et Unobstrusive JS <%= link_to “Delete”, @article, :method => :delete %> <a href="#" title="Delete" onclick="var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = Rails 2 this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'XXX...XXX'); f.appendChild(s);f.submit(); return false;">Delete</a> Rails 3 <a href=”/articles/1” data-method=”delete” rel=”nofollow”>Delete</a> 22/25
  • 23. XSS et Unobstrusive JS <%= link_to “Delete”, @article, :method => :delete, :confirm => “Are you sure ?” %> <a href="#" title="Delete" onclick="if (confirm(“Are you sure ?”)) {var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = Rails 2 this.href;var s = document.createElement('input'); s.setAttribute('type', 'hidden'); s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'XXX...XXX'); f.appendChild(s);f.submit();} return false;">Delete</a> Rails 3 <a href=”/articles/1” data-method=”delete” data-confirm=”Are you sure ?” rel=”nofollow”>Delete</a> 23/25
  • 24. Prochaine étape Rails 3.1 • jQuery • CoffeeScript • Sass 24/25
  • 25. Prochaine étape number = 42 if true square = (x) -> x * x alert "Hello" if number? list = [1, 2, 3, 4] Rails 3.1 squares = (square num for num in list) var number, square, list, squares, num; • jQuery if (true) { number = 42; } • CoffeeScript square = function(x) { return x * x; }; if (typeof number !== "undefined" && number !== null) { • Sass } alert("Hello"); squares = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(square(num)); } return _results; })(); 25/25
  • 26. Prochaine étape table.hl margin: 2em 0 td.ln text-align: right Rails 3.1 li font: family: serif weight: bold jQuery size: 1.2em • • CoffeeScript table.hl { margin: 2em 0; } table.hl td.ln { • Sass } text-align: right; li { font-family: serif; font-weight: bold; font-size: 1.2em; } 26/25
  • 27. Prochaine étape table.hl margin: 2em 0 td.ln text-align: right Rails 3.1 li font: family: serif weight: bold jQuery size: 1.2em • • CoffeeScript table.hl { margin: 2em 0; } table.hl td.ln { • Sass } text-align: right; li { font-family: serif; font-weight: bold; font-size: 1.2em; } 27/25
  • 28. Merci de votre attention Cont act : LINAGORA - Siège social 80, rue Roque de Fillol 92800 PUTEAUX FRANCE Tél. : 0 810 251 251 (t arif local) Fax : +33 (0)1 46 96 63 64 Mail : info@linagora.com Web : www.linagora.com 28 WWW.LINAGORA.COM