Upload
whitesmith
View
230
Download
0
Embed Size (px)
Citation preview
Desenvolvimento Web
com Ruby on Rails
Nuno Silva@nunosilva800
www.whitesmith.co
● Criação
● Objectivos principais
● Inspirada em Perl, Smalltalk, Eiffel, Ada e Lisp
RUBY
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
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
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
Semelhanças
● Garbage Collector
● Tipagem forte
○ Ruby: dinâmica / Java: estática
● Public, Private, Protected methods
DO JAVA PARA O RUBY
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
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
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
● 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
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
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
$ 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
$ rails db:create$ rails server$ xdg-open http://localhost:3000
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
$ rails db:migrate$ rails server
Demo Time!
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
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
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
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
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
$ 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
E como é lá fora?
Construído com Ruby on Rails até ~ 2011.Trocaram para Scala devido à enorme demanda.
Obrigado!
Nuno Silva@nunosilva800
www.whitesmith.co
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