30
Desenvolvimento Web com Ruby on Rails Nuno Silva @nunosilva800 www.whitesmith.co

Quick introduction to Ruby on Rails

Embed Size (px)

Citation preview

Page 1: Quick introduction to Ruby on Rails

Desenvolvimento Web

com Ruby on Rails

Nuno Silva@nunosilva800

www.whitesmith.co

Page 2: Quick introduction to Ruby on Rails
Page 3: Quick introduction to Ruby on Rails
Page 4: Quick introduction to Ruby on Rails

● Criação

● Objectivos principais

● Inspirada em Perl, Smalltalk, Eiffel, Ada e Lisp

RUBY

Page 5: Quick introduction to Ruby on Rails

Tudo é um objecto. Até os tipos primitivos!

irb> 3.times { puts "Eu amo Ruby <3" }Eu amo Ruby <3Eu amo Ruby <3Eu amo Ruby <3

irb> nil.inspect=> "nil"

irb> nil.to_s=> ""

irb> nil.to_i=> 0

irb> nil.nil?=> true

irb> 3.14159.negative?=> false

irb> 1_500_000 == 1500000=> true

RUBY

Page 6: Quick introduction to Ruby on Rails

Tudo é um objecto. Até os tipos primitivos!

irb> [1,2,3].max=> 3

irb> soma = 0irb> [1,2,3].each { |n| soma += n }irb> soma=> 6

irb> [1,2,3].inject { |acc, n| acc += n }=> 6

irb> [1,2,3].inject(&:+)=> 6

RUBY

Page 7: Quick introduction to Ruby on Rails

Tudo é um objecto. Até os tipos primitivos!

irb> my_hash = {a: 1, b: 'foo', c: [1,2,3]}=> {:a=>1, :b=>"foo", :c=>[1, 2, 3]}

irb> my_hash[:b]=> "foo"

irb> my_hash.values=> [1, "foo", [1, 2, 3]]

RUBY

Page 8: Quick introduction to Ruby on Rails

Semelhanças

● Garbage Collector

● Tipagem forte

○ Ruby: dinâmica / Java: estática

● Public, Private, Protected methods

DO JAVA PARA O RUBY

Page 9: Quick introduction to Ruby on Rails

Diferenças

● Sem compilação (interpretado)

● end ao invés de colchetes {}

● require ao invés de import

● Sem declarações de tipos a = [1,2,3]vs int[] a = {1,2,3};

● foo = Foo.new("hi") ao invés de Foo foo = new Foo("hi")

● Construtor é sempre chamado de initialize

● Variáveis de instância são todas privadas

DO JAVA PARA O RUBY

Page 10: Quick introduction to Ruby on Rails

class Animal def say nil endend

class Dog < Animal def say 'Woff' endend

class Fox < Animal # what does the fox say?end

> Animal.new.say => nil

> Dog.new.say => "Woff"

> Fox.new.say => nil

RUBY

Page 11: Quick introduction to Ruby on Rails

class Counter def initialize @value = 0 end

def add @value += 1 end

def current @value endend

> counter = Counter.new => #<Counter:0x000000034ca448 @value=0>

> counter.current => 0

> counter.add => 1

> counter.current => 1

> counter.valueNoMethodError: undefined method `value'

> counter.@valueSyntaxError:

RUBY

Page 12: Quick introduction to Ruby on Rails

● Matz’s Ruby Interpreter (MRI) / CRuby○ Oficial, implementado em C○ Acesso a bibliotecas escritas em C

● JRuby○ Implementado em Java, roda na JVM○ Acesso a bibliotecas escritas em Java

● RubyMotion○ Implementado em Objective-C / Cocoa○ Gera binários nativos para iOS, OS X e Android

● mruby○ Versão embutível do MRI, para sistemas embarcados○ Ideal para rodar Ruby em Raspberry Pi, IoTs, etc.

Interpretadores Ruby

RUBY

Page 13: Quick introduction to Ruby on Rails

Rubygems.org

$ gem install bundlerFetching: bundler-1.13.5.gem (100%)Successfully installed bundler-1.13.5

Bundler.io

source 'https://rubygems.org'gem 'rails'gem 'jquery-rails', '~> 3.1.3'

$ bundle installFetching gem metadata from https://rubygems.org/.....

RUBY

Page 14: Quick introduction to Ruby on Rails
Page 15: Quick introduction to Ruby on Rails

O que é o Ruby on Rails?

● Framework para desenvolvimento Web

● Open source

● Full-stack: do banco de dados ao cliente (browser)

● RESTful

● Valoriza a convenção ao invés da configuração

RUBY ON RAILS

Page 16: Quick introduction to Ruby on Rails

$ gem install rails$ rails new semana-academica --database=postgresql$ cd semana-academica

├── app├── bin├── config├── db├── Gemfile├── Gemfile.lock├── lib├── log├── public├── test└── vendor

app/├── assets├── channels├── controllers├── helpers├── jobs├── mailers├── models└── views

RUBY ON RAILS

Page 17: Quick introduction to Ruby on Rails

$ rails db:create$ rails server$ xdg-open http://localhost:3000

RUBY ON RAILS

Page 18: Quick introduction to Ruby on Rails

$ rails generate scaffold post title:string body:text

invoke active_recordcreate db/migrate/20161017203634_create_posts.rbcreate app/models/post.rbinvoke resource_route route resources :postsinvoke scaffold_controllercreate app/controllers/posts_controller.rbinvoke erbcreate app/views/postscreate app/views/posts/index.html.erbcreate app/views/posts/edit.html.erbcreate app/views/posts/show.html.erbcreate app/views/posts/new.html.erbcreate app/views/posts/_form.html.erbinvoke test_unitcreate test/models/post_test.rbcreate test/fixtures/posts.ymlcreate test/controllers/posts_controller_test.rb

RUBY ON RAILS

Page 19: Quick introduction to Ruby on Rails

$ rails db:migrate$ rails server

Demo Time!

RUBY ON RAILS

Page 20: Quick introduction to Ruby on Rails

MVC - Camada de dados + modelosclass CreatePosts < ActiveRecord::Migration[5.0] def change create_table :posts do |t| t.string :title t.text :body

t.timestamps end endend

class Post < ApplicationRecordend

RUBY ON RAILS

Page 21: Quick introduction to Ruby on Rails

MVC - Camada de controladores + rotas

$ rails routes Prefix Verb URI Pattern Controller#Action posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#newedit_post GET /posts/:id/edit(.:format) posts#edit post GET /posts/:id(.:format) posts#show PATCH /posts/:id(.:format) posts#update PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy

Rails.application.routes.draw do resources :postsend

RUBY ON RAILS

Page 22: Quick introduction to Ruby on Rails

MVC - Camada de controladores + rotasclass PostsController < ApplicationController

# GET /posts # GET /posts.json def index @posts = Post.all end

# GET /posts/1 # GET /posts/1.json def show

@post = Post.find(params[:id]) end

# GET /posts/new def new @post = Post.new end

RUBY ON RAILS

Page 23: Quick introduction to Ruby on Rails

MVC - Camada de visão

<p> <strong>Title:</strong> <%= @post.title %></p>

<p> <strong>Body:</strong> <%= @post.body %></p>

<%= link_to 'Edit', edit_post_path(@post) %> |<%= link_to 'Back', posts_path %>

$ cat semana-academica/app/views/posts/show.html.erb

RUBY ON RAILS

Page 24: Quick introduction to Ruby on Rails

MVC - Camada de visão

json.partial! "posts/post", post: @post

json.extract! post, :id, :title, :body, :created_at, :updated_atjson.url post_url(post, format: :json)

$ curl http://localhost:3000/posts/1.json{"id":1,"title":"Olá Unitins","body":"Semana acadêmica \\o/","created_at":"2016-10-17T21:20:05.247Z","updated_at":"2016-10-17T21:20:05.247Z","url":"http://localhost:3000/posts/1.json"}

$ cat semana-academica/app/views/posts/show.json.jbuilder

$ cat semana-academica/app/views/posts/_post.json.jbuilder

RUBY ON RAILS

Page 25: Quick introduction to Ruby on Rails

$ rails console

> Post.count (0.2ms) SELECT COUNT(*) FROM "posts" => 1

> Post.first Post Load (0.6ms) SELECT "posts".* FROM "posts" ORDER BY "posts"."id" ASC LIMIT $1 [["LIMIT", 1]] => #<Post id: 1, title: "Olá Unitins", body: "Semana acadêmica \\o/",...>

> Post.where(created_at: (Date.today - 1.day)..(Date.today + 1.day)).count (0.8ms) SELECT COUNT(*) FROM "posts" WHERE ("posts"."created_at" BETWEEN $1 AND $2) [["created_at", Sun, 16 Oct 2016], ["created_at", Tue, 18 Oct 2016]] => 1

RUBY ON RAILS

Page 26: Quick introduction to Ruby on Rails

E como é lá fora?

Page 27: Quick introduction to Ruby on Rails
Page 28: Quick introduction to Ruby on Rails

Construído com Ruby on Rails até ~ 2011.Trocaram para Scala devido à enorme demanda.

Page 29: Quick introduction to Ruby on Rails

Obrigado!

Nuno Silva@nunosilva800

www.whitesmith.co

Page 30: Quick introduction to Ruby on Rails

Do Java para RubyPerformance

Ruby 2.3 ~ 4% mais lento que Java 8

https://github.com/famzah/langs-performance

http://benchmarksgame.alioth.debian.org/u64q/compare.php?lang=yarv&lang2=java