Slide 1

Slide 1 text

Introduction à Ruby Rémi Prévost — Web à Québec 2012

Slide 2

Slide 2 text

Rémi Prévost Développeur Web qui aime Ruby freelance!

Slide 3

Slide 3 text

Objectif

Slide 4

Slide 4 text

Vous convaincre d’essayer Ruby!

Slide 5

Slide 5 text

Simple à apprendre

Slide 6

Slide 6 text

Rapide à débuter

Slide 7

Slide 7 text

Naturel à écrire

Slide 8

Slide 8 text

Sondage rapide

Slide 9

Slide 9 text

Ruby, le langage Ruby et le Web Introduction à Ruby

Slide 10

Slide 10 text

Ruby, le langage

Slide 11

Slide 11 text

“I’ve made a huge mistake.”

Slide 12

Slide 12 text

Historique Installation Types de données Syntaxe particulière Modèle objet Gems Ruby, le langage

Slide 13

Slide 13 text

Minute historique

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Installer Ruby

Slide 16

Slide 16 text

$ ruby -v ruby 1.8.7 (2010-01-10 patchlevel 249) Mac OS X

Slide 17

Slide 17 text

$ brew install rbenv ruby-build $ rbenv install 1.9.2-p290 Mac OS X

Slide 18

Slide 18 text

$ sudo apt-get install ruby-1.9.1-full Ubuntu/Debian

Slide 19

Slide 19 text

Windows

Slide 20

Slide 20 text

$ irb ruby-1.9.2-p290 :001 >

Slide 21

Slide 21 text

Hello World

Slide 22

Slide 22 text

# Contenu de hello.rb puts("Hello World.") $ ruby hello.rb Hello World.

Slide 23

Slide 23 text

Types de données

Slide 24

Slide 24 text

# Fixnum 7 # String "foo" # Array [4, 7, 15, 16, 23, 42] # Hash { :foo => "bar", :omg => 3 }

Slide 25

Slide 25 text

# Symbol :foo # Regex /[a-z]{0,10}\s+$/i # Proc lambda { |args| return "hello" } # NilClass nil

Slide 26

Slide 26 text

Syntaxe pensée pour les développeurs

Slide 27

Slide 27 text

puts "Hello world." # puts("Hello world.") puts :foo => :bar, :omg => 3 # puts({ :foo => :bar, :omg => 3 })

Slide 28

Slide 28 text

nombres = ["un", "deux", "trois"] nombres.empty? => false nombres.first => "un" nombres.include? "deux" => true

Slide 29

Slide 29 text

puts "Hello" if total == 2 # ou if total == 2 puts "Hello" end

Slide 30

Slide 30 text

def hello(name) another_method("foo") return "Hello, #{name.capitalize}" end # ou def hello(name) another_method("foo") "Hello, #{name.capitalize}" end hello("rémi") => "Hello, Rémi"

Slide 31

Slide 31 text

[1, 2, 3].map { |x| x * 2 } # ou [1, 2, 3].map do |x| x * 2 end => [2, 4, 6]

Slide 32

Slide 32 text

Modèle objet simple

Slide 33

Slide 33 text

Tout est un objet

Slide 34

Slide 34 text

Tout?

Slide 35

Slide 35 text

Tout!

Slide 36

Slide 36 text

upcase("foo") => NoMethodError: undefined method `upcase' for main:Object "foo".upcase => FOO

Slide 37

Slide 37 text

"foo".upcase => "FOO" 108.to_s => "108" [1, 2, 3, 4].shuffle => [2, 4, 1, 3] { :foo => "bar", :omg => 3 }.keys => [:foo, :omg]

Slide 38

Slide 38 text

10.times { |i| puts i } 0 1 2 3 4 5 6 7 8 9

Slide 39

Slide 39 text

2 + 3 # ou # 2.+(3) => 5 [1, 2, 3] << 4 # ou # [1, 2, 3].<<(4) => [1, 2, 3, 4]

Slide 40

Slide 40 text

puts "Hello World." # Kernel.puts("Hello World.") require "../fichier.rb" # Kernel.require("../fichier.rb")

Slide 41

Slide 41 text

Définir nos propres classes

Slide 42

Slide 42 text

class Article end article = Article.new => #

Slide 43

Slide 43 text

class Article < Contenu attr_reader :published def initialize(published=true) @published = published end def publish! @published = true end end article = Article.new(false) article.publish! article.published => true

Slide 44

Slide 44 text

Modèle objet souple

Slide 45

Slide 45 text

Classes modifiables

Slide 46

Slide 46 text

class Article def delete puts "Suppression de l’article!" end end class Article def delete puts "Finalement, on ne fait rien!" end end article = Article.new article.delete => "Finalement, on ne fait rien!"

Slide 47

Slide 47 text

class Article def delete puts "Suppression de l’article!" end end article = Article.new class Article def delete puts "Finalement, on ne fait rien!" end end article.delete => "Finalement, on ne fait rien!"

Slide 48

Slide 48 text

Classes internes modifiables (au runtime!)

Slide 49

Slide 49 text

class String def sans_les_voyelles self.gsub /[aeiouy]/i, "" end end "webaquebec".sans_les_voyelles => "wbqbc"

Slide 50

Slide 50 text

class Fixnum def minutes self * 60 end def hours self * 60.minutes end end 2.minutes => 120 5.hours => 18000

Slide 51

Slide 51 text

class Object def lol! "LOL!" end end 1.lol! => "LOL!" "Test".lol! => "LOL!" [1, 2, 3].lol! => "LOL!"

Slide 52

Slide 52 text

class NilClass def really? "Yep, really!" end end foo = nil foo.really? => "Yep, really!"

Slide 53

Slide 53 text

Extension via modules

Slide 54

Slide 54 text

module SuperModule def super! "Hé, #{self}, super!" end end class String include SuperModule end "Web à Québec".super! => "Hé, Web à Québec, super!"

Slide 55

Slide 55 text

Librairies externes centralisées

Slide 56

Slide 56 text

$ ls /var/www/mon-application-php wp-atom.php wp-feed.php index.php wp-blog-header.php wp-includes/ license.txt wp-comments-post.php wp-opml.php wp-login.php wp-commentsrss2.php wp-load.php wp-pass.php readme.html wp-config.php wp-rdf.php wp-activate.php wp-mail.php wp-admin/ wp-content/ wp-app.php wp-cron.php $ ls /var/www/mon-application-ruby Gemfile Gemfile.lock config.ru app.rb

Slide 57

Slide 57 text

Gems (moi je dis « une gem »)

Slide 58

Slide 58 text

$ gem install httparty Fetching: multi_xml-0.4.1.gem (100%) Fetching: httparty-0.8.1.gem (100%) When you HTTParty, you must party hard! Successfully installed multi_xml-0.4.1 Successfully installed httparty-0.8.1 2 gems installed $ irb >> HTTParty NameError: uninitialized constant Object::HTTParty >> require "httparty" => true >> HTTParty => HTTParty

Slide 59

Slide 59 text

$ bundle --version command not found: bundle $ gem install bundler Successfully installed bundler-1.0.22 1 gem installed $ bundle --version Bundler version 1.0.22

Slide 60

Slide 60 text

Ruby et le Web (à Québec)

Slide 61

Slide 61 text

Historique Rack Frameworks • Rails • Sinatra Hébergement + déploiement Ruby et le Web

Slide 62

Slide 62 text

Minute historique

Slide 63

Slide 63 text

DHH

Slide 64

Slide 64 text

Rack (une structure pour faire du Web)

Slide 65

Slide 65 text

$ tree . . !"" a-propos.rb !"" index.rb #"" projets.rb 0 directories, 3 files $ curl http://localhost/index.rb Ma page d’accueil! $ curl http://localhost/a-propos.rb Moi, bla bla bla. NOPE

Slide 66

Slide 66 text

Rack (une structure pour faire du Web)

Slide 67

Slide 67 text

Interface serveur + code

Slide 68

Slide 68 text

Utilisateur Serveur Web Rack Ruby Rack Serveur Web Utilisateur Requête HTTP

Slide 69

Slide 69 text

# Contenu de config.ru class Blogue def call(env) headers = { "Content-type" => "text/html" } [200, headers, "Hello world."] end end run Blogue.new

Slide 70

Slide 70 text

$ gem install rack $ rackup config.ru WEBrick 1.3.1 ruby 1.9.2 (2011-07-09) WEBrick::HTTPServer#start: pid=69232 port=9292 $ curl http://localhost:9292 Hello world. $ curl http://localhost:9292/foo/bar Hello world.

Slide 71

Slide 71 text

Ruby on Rails

Slide 72

Slide 72 text

“Full stack”

Slide 73

Slide 73 text

ORM AJAX EMAIL TESTS MVC SESSIONS CSRF ROUTES DATABASE

Slide 74

Slide 74 text

“Convention over configuration”

Slide 75

Slide 75 text

Utilisateur Serveur Web Rack Rails Rack Serveur Web Utilisateur Requête HTTP Ruby

Slide 76

Slide 76 text

$ rails new mon_application … $ du --max-depth 1 -h . 28K ./app 60K ./config 4,0K ./db 4,0K ./doc 0 ./lib 0 ./log 24K ./public 4,0K ./script 8,0K ./test 0 ./tmp 0 ./vendor 164K .

Slide 77

Slide 77 text

Ruby on Sinatra

Slide 78

Slide 78 text

“Micro-framework”

Slide 79

Slide 79 text

ORM AJAX EMAIL TESTS MVC SESSIONS CSRF ROUTES DATABASE

Slide 80

Slide 80 text

“Add as you grow”

Slide 81

Slide 81 text

Utilisateur Serveur Web Rack Sinatra Rack Serveur Web Utilisateur Requête HTTP Ruby

Slide 82

Slide 82 text

Configuration (Bundler) Données (DataMapper) Routes Vues (Haml) Sinatra

Slide 83

Slide 83 text

Surprise, un blogue!

Slide 84

Slide 84 text

$ tree . . !"" Gemfile !"" config.ru #"" blogue.rb 0 directories, 3 files

Slide 85

Slide 85 text

Configuration (avec Bundler)

Slide 86

Slide 86 text

# Contenu de Gemfile source "http://rubygems.org" gem "sinatra" gem "dm-core" gem "dm-mysql-adapter" gem "dm-migrations" gem "haml"

Slide 87

Slide 87 text

# Contenu de Gemfile source "http://rubygems.org" gem "sinatra", "~> 1.3" gem "dm-core" gem "dm-mysql-adapter" gem "dm-migrations" gem "haml", "3.1"

Slide 88

Slide 88 text

$ bundle install => Fetching gem metadata from http://rubygems.org/ Installing addressable (…) Installing data_objects (…) Installing dm-core (…) Installing dm-mysql-adapter (…) Installing dm-migrations (…) Installing rack (…) Installing tilt (…) Installing sinatra (…) Installing haml (…) Using bundler (…) Your bundle is complete!

Slide 89

Slide 89 text

# Contenu de config.ru require "bundler" Bundler.require require "./blogue.rb" run Sinatra::Application

Slide 90

Slide 90 text

$ rackup config.ru WEBrick 1.3.1 ruby 1.9.2 (2011-07-09) WEBrick::HTTPServer#start: pid=69232 port=9292

Slide 91

Slide 91 text

Données (avec DataMapper)

Slide 92

Slide 92 text

# Contenu de blogue.rb configure do DataMapper::Logger.new(STDOUT, :debug) DataMapper.setup(:default, "mysql://localhost/blogue") end class Article include DataMapper::Resource # Un module! property :id, Serial property :title, String property :content, Text property :created_at, DateTime end DataMapper.finalize DataMapper.auto_upgrade!

Slide 93

Slide 93 text

Article.all => [#, #, …] Article.all(:created_at.gte => Time.now - 3600) => [#] Article.get(42) => # Article.create(:title => "Hello!") => # Article.all(:title => "Un test").destroy => true

Slide 94

Slide 94 text

Routes

Slide 95

Slide 95 text

get "/" do … end post "/articles" do … end put "/articles/:id" do … end delete "/articles/:id" do … end

Slide 96

Slide 96 text

get "/articles/:id" do # params[:id] end get /\/articles\/(?[0-9]+)/ do # params[:id] end get "/articles/*" do # params[:splat] end get "/articles/:id.?:format?" do # params[:id], params[:format] end

Slide 97

Slide 97 text

get "/" do @articles = Article.all end get "/articles/:id" do @article = Article.get(params[:id]) end

Slide 98

Slide 98 text

post "/articles" do @article = Article.create(params[:article]) redirect to("/articles/#{@article.id}") end

Slide 99

Slide 99 text

$ curl http://localhost:9292/articles -X POST --data "article[title]=Mon+article" --data "article[content]=Le+contenu" params => { :article => { :title => "Mon article", :content => "Mon contenu" } }

Slide 100

Slide 100 text

Vues (avec Haml)

Slide 101

Slide 101 text

get "/" do @articles = Article.all end get "/articles/:id" do @article = Article.find(params[:id]) end

Slide 102

Slide 102 text

get "/" do @articles = Article.all "Il y a #{@articles.length} articles." end get "/articles/:id" do @article = Article.get(params[:id]) "C’est bien #{@article.title}." end

Slide 103

Slide 103 text

get "/" do @articles = Article.all haml :index end get "/articles/:id" do @article = Article.get(params[:id]) haml :show end

Slide 104

Slide 104 text

Introduction à Haml

Slide 105

Slide 105 text

%h1 Hello world. %p Voici une liste : %ul %li %a{ :href => "http://exomel.com" } Rémi

Hello world.

Voici une liste :

Slide 106

Slide 106 text

Fin de l’introduction à Haml

Slide 107

Slide 107 text

-# Contenu de views/index.haml %ul - @articles.each do |article| %li %h1= article.title = article.content

Slide 108

Slide 108 text

-# Contenu de views/show.haml %h1= @article.title = @article.content

Slide 109

Slide 109 text

get "/" do @articles = Article.all haml :index, :layout => :blogue end get "/articles/:id" do @article = Article.get(params[:id]) haml :show, :layout => :blogue end

Slide 110

Slide 110 text

-# Contenu de views/blogue.haml !!! 5 %title Mon blogue %body = yield

Slide 111

Slide 111 text

-# Exemple de http://localhost/articles/1 Mon blogue

Lorem Ipsum

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla dignissim, libero quis dapibus scelerisque

Slide 112

Slide 112 text

Le code final

Slide 113

Slide 113 text

# Contenu de blogue.rb configure do DataMapper::Logger.new STDOUT, :debug DataMapper.setup :default, "mysql://localhost/blogue" class Article include DataMapper::Resource property :id, Serial property :title, String property :content, Text property :created_at, DateTime end DataMapper.finalize DataMapper.auto_upgrade! end

Slide 114

Slide 114 text

# Suite de blogue.rb get "/" do @articles = Article.all haml :index, :layout => :blogue end get "/articles/:id" do @article = Article.get(params[:id]) haml :show, :layout => :blogue end post "/articles" do @article = Article.create(params[:article]) redirect to("/article/#{@article.id}") end

Slide 115

Slide 115 text

-# Contenu de views/index.haml %ul - @articles.each do |article| %li %h1= article.title = article.content -# Contenu de views/show.haml %h1= @article.title = @article.content -# Contenu de views/blogue.haml !!! 5 %title Mon blogue %body = yield

Slide 116

Slide 116 text

configure do DataMapper::Logger.new STDOUT, :debug DataMapper.setup :default, "mysql://localhost/blogue" class Article include DataMapper::Resource property :id, Serial property :title, String property :content, Text property :created_at, DateTime end DataMapper.finalize DataMapper.auto_upgrade! end get "/" do @articles = Article.all haml :index, :layout => :blogue end get "/articles/:id" do @article = Article.find(params[:id]) haml :show, :layout => :blogue end post "/articles" do @article = Article.create(params[:article]) redirect to("/article/#{@article.id}") end

Slide 117

Slide 117 text

Hébergement et déploiement

Slide 118

Slide 118 text

Le mythe (« omg, ruby c’est compliqué! »)

Slide 119

Slide 119 text

Heroku (la magie)

Slide 120

Slide 120 text

$ gem install heroku $ heroku apps:create blogue Creating blogue... done Git remote heroku added $ git push heroku master -----> Heroku receiving push -----> Ruby/Rack app detected -----> Gemfile detected, running Bundler version 1.0.7 Unresolved dependencies detected; Installing... Your bundle is complete! -----> Launching... done, v1 http://blogue.heroku.com deployed to Heroku

Slide 121

Slide 121 text

mod_passenger (la transition idéale)

Slide 122

Slide 122 text

$ sudo gem install passenger $ sudo passenger-install-apache2-module LoadModule passenger_module /usr/lib/ruby/gems/ 1.9.1/gems/passenger-3.0.11/ext/apache2/ mod_passenger.so PassengerRoot /usr/lib/ruby/gems/1.9.1/gems/ passenger-3.0.11 PassengerRuby /usr/bin/ruby1.9.1

Slide 123

Slide 123 text

ServerName blogue.webaquebec.org DocumentRoot /var/www/blogue/public Allow from all Options -MultiViews $ cd /var/www/blogue $ mkdir public $ mkdir tmp $ sudo apachectl restart

Slide 124

Slide 124 text

$ touch tmp/restart.txt

Slide 125

Slide 125 text

Résumé (en 30 secondes)

Slide 126

Slide 126 text

$ sudo gem install sinatra $ cat config.ru require "sinatra" get "/" do "Hello world." end run Sinatra::Application $ rackup config.ru WEBrick 1.3.1 ruby 1.9.2 (2011-07-09) WEBrick::HTTPServer#start: pid=69232 port=9292

Slide 127

Slide 127 text

Ressources utiles

Slide 128

Slide 128 text

Ressources utiles

Slide 129

Slide 129 text

Ressources utiles • sinatrarb.com • guides.rubyonrails.org • haml-lang.com • github.com/explore/languages/ruby • heroku.com • modrails.com (Apache et nginx)

Slide 130

Slide 130 text

Merci! Rémi Prévost — http://exomel.com @remi