42
Introdução ao Ruby on Rails Introdução ao Ruby on Rails

Introdução ao Ruby on Rails

Embed Size (px)

Citation preview

Page 1: Introdução ao Ruby on Rails

Introdução ao Ruby on Rails

Introdução ao Ruby on Rails

Page 2: Introdução ao Ruby on Rails

Juan Maiz Lulkin Flores da Cunha

Introdução ao Ruby on Rails > Palestrante

WWR person/9354vice-campeão mundial dedefender of the favicon

Page 3: Introdução ao Ruby on Rails

HistóriaDavid Heinemeier Hanson (DHH)Martin Fowler37Signals

Introdução ao Ruby on Rails > História

Page 4: Introdução ao Ruby on Rails

Ruby on RailsRubyModel View ControllerPrincípiosComunidadeAnd so much more

Introdução ao Ruby on Rails > Ruby on Rails

Page 5: Introdução ao Ruby on Rails

RubySmalltalk elegância conceitual

Python facilidade de uso

Perl pragmatismo

Introdução ao Ruby on Rails > Ruby on Rails > Ruby

Page 6: Introdução ao Ruby on Rails

Smalltalk1 + 1 => 2

1.+(1) => 2 1.send('+',1) => 2

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Smalltalk

Page 7: Introdução ao Ruby on Rails

Pythonfor 1 in 1..10 puts iend 1 2 3 4 5 6 7

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Python

Page 8: Introdução ao Ruby on Rails

Perlls = %w{smalltalk python perl} => ["smalltalk", "python", "perl"]

ls.map{|l| “Ruby é como #{l}. ” }.join => “Ruby é como smalltalk. Ruby é como python. Ruby é como perl.

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Perl

Page 9: Introdução ao Ruby on Rails

Ruby5.times{ p “ybuR olleH”.reverse } "Hello Ruby" "Hello Ruby" "Hello Ruby" "Hello Ruby" "Hello Ruby" => 5

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Hello

Page 10: Introdução ao Ruby on Rails

RubyTotalmente OOMixins (toma essa!)Classes “abertas”BlocosBibliotecas

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos

Page 11: Introdução ao Ruby on Rails

Totalmente OO42.class => FixnumFixnum.class => Class

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Totalmente OO

Page 12: Introdução ao Ruby on Rails

Mixins (toma essa!)module Cool def is_cool! “#{self} is cool!” endend

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Mixins (toma essa!)

Page 13: Introdução ao Ruby on Rails

Classes “abertas”class String include Coolendputs “Ruby”.is_cool! Ruby is cool!

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Classes “abertas”

Page 14: Introdução ao Ruby on Rails

Blocos[16,19,21,15].select{|n| n > 17} => [19,21][1,2,3].map{|n| n*2 } => [2,4,6][5,6,7,8].sort_by{ … }File.open('file.txt').each_line{ … }Dir.glob('*.rb').each{ … }Benchmark.measure { ... }

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Blocos

Page 15: Introdução ao Ruby on Rails

BibliotecasHpricot + OpenUri

Hpricot(open 'http://ab.com').search('a').map{|a| a[:href]}Prawn

Prawn::Document.new.text(“Hello PDF”)RedCloth

RedCloth.new(“Hello *Textile*”).to_htmlRMagick

Image.read('i.pdf').first.write('i.png'){self.quality = 80}Shoes

Shoes.app{ button "Hello Windows" }RubyGame

Game.new.when_key_pressed(:q){ exit }Geokit

YahooGeocoder.geocode 'Rua Vieira de Casto 262'

Introdução ao Ruby on Rails > Ruby on Rails > Ruby > Conceitos > Bibliotecas

Page 16: Introdução ao Ruby on Rails

Model View ControllerModel dados e lógica de domínio

View interface

Controller caminhos e distribuição

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller

Page 17: Introdução ao Ruby on Rails

ModelActiveRecordMigraçõesOperações básicasRelaçõesValidaçõesActs asNamed scopesAdicionar métodos

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model

Page 18: Introdução ao Ruby on Rails

Migraçõesclass CreateEvents < ActiveRecord::Migration def self.up create_table :events do |t| t.string :name, :null => false t.boolean :active, :default => true t.integer :year, :null => false t.timestamps end endend

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Migrações

Page 19: Introdução ao Ruby on Rails

Operações básicasInsertEvent.create :name => 'RS on Rails', :year => Date.today.yeare = Event.newe.name = 'RS on Rails'e.year = 2009e.save

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas

Page 20: Introdução ao Ruby on Rails

Operações básicasSelectEvent.all :conditions => 'active', :order => 'created_at', :l imit => 10e = Event.firste = Event.find 1e = Event.find_by_name 'RS on Rails'e = Event.find_by_year 2009

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas

Page 21: Introdução ao Ruby on Rails

Operações básicasUpdateEvent.update_all 'active = true'e = Event.firste.name = 'other name'e.savee.update_attribute :active => falsee.toggle! :active

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas

Page 22: Introdução ao Ruby on Rails

Operações básicasDeleteEvent.delete_alle = Event.firste.destroy

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Operações básicas

Page 23: Introdução ao Ruby on Rails

Relaçõesclass Event < ActiveRecord::Base has_many :talksendclass Talk < ActiveRecord::Base belongs_to :event has_one :speakerend

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações

Page 24: Introdução ao Ruby on Rails

Relaçõesrsr = Event.find_by_name('rsrails')talk = rsr.talks.firsttalk.name => “Introdução ao Ruby on Rails”

talk.speaker.name => “Juan Maiz Lulkin”

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Relações

Page 25: Introdução ao Ruby on Rails

Validaçõesclass Event < ActiveRecord::Base validates_presence_of :name, :year validates_numericality_of :year validates_inclusion_of :year,

:in => 2009..2099 validates_length_of :name,

:minimum => 4 validates_format_of :name,

:with => /[A-Z]\d+/end

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Validações

Page 26: Introdução ao Ruby on Rails

Acts Asclass Category < ActiveRecord::Base acts_as_treeenbCategory.find(10).parentCategory.find(20).children

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as

Page 27: Introdução ao Ruby on Rails

Acts Asclass Doc < ActiveRecord::Base acts_as_versionedenddoc = Doc.create :name = '1 st name'doc.version => 1

doc.update_attribute :name, '2nd name'doc.version => 2

doc.revert_to(1)doc.name => 1 st name

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Acts as

Page 28: Introdução ao Ruby on Rails

Named scopesclass Product < ActiveRecord::Base named_scope :top, :order => 'rank desc' named_scope :ten, :limit => 10 named_scope :between, lambda{|min,max| {:conditions => [“price between ? and ?”, min, max]}}endProduct.between(0,100).top.ten

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Named scopes

Page 29: Introdução ao Ruby on Rails

Adicionar métodosclass Product < ActiveRecord::Base def +(product) price + product.price endendfoo = Product.find(1)bar = Product.find(2)foo + bar

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Model > Adicionar métodos

Page 30: Introdução ao Ruby on Rails

ControllerURL: http://seusite.com/events/rsrails

class EventsController < ApplicationController def show name = params[:id] @event = Event.find_by_name(name) endend

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Controller

Page 31: Introdução ao Ruby on Rails

Viewapp/views/events/show.html.haml

#content %h1 Palestras %ul - for talk in @event.talks %li= talk.title

* Você está usando HAML, não?

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > View

Page 32: Introdução ao Ruby on Rails

PrincípiosConvention Over Configuration Se é usado na maior parte dos casos, deve ser o padrão.Don't Repeat Yourself Mixins, plugins, engines, gems...

Métodos ágeis BDD, TDD, integração contínua, deployment...

Introdução ao Ruby on Rails > Ruby on Rails > Princípios

Page 33: Introdução ao Ruby on Rails

Convention Over ConfigurationXML YAMLdevelopment: adapter: postgresql encoding: unicode database: events_development pool: 5 username: event_admin password: *****

Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC

Page 34: Introdução ao Ruby on Rails

Convention Over Configurationrsrails = Event.find(1) => assume campo “id” na tabela “events”

rsrails.talks => assume uma tabela “talks” com um fk “event_id”rsrails.talks.first.speaker => assume campo “speaker_id” em “talks” como fk para tabela “speakers”

Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC

Page 35: Introdução ao Ruby on Rails

Convention Over Configurationscript/generate scaffold Event

name:stringyear:integeractive:boolean

Introdução ao Ruby on Rails > Ruby on Rails > Princípios > CoC

Page 36: Introdução ao Ruby on Rails

Don't Repeat Yourselfactive_scaffoldlink_to loginimage_tag 'star.png' * hotel.starsrender :partial => 'event',

:collection => @events

Introdução ao Ruby on Rails > Ruby on Rails > Princípios > DRY

Page 37: Introdução ao Ruby on Rails

Métodos ágeisclass EventTest < ActiveSupport::TestCase test "creation" do assert Event.create :name => 'rsrails',

:year => 2009 endend

Introdução ao Ruby on Rails > Ruby on Rails > Princípios > Métodos ágeis

Page 38: Introdução ao Ruby on Rails

Métodos ágeisrake integratecap deploy

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis

Page 39: Introdução ao Ruby on Rails

Métodos ágeisGetting Realhttp://gettingreal.37signals.com/

Introdução ao Ruby on Rails > Ruby on Rails > Model View Controller > Princípios > Métodos ágeis

Page 40: Introdução ao Ruby on Rails

ComunidadeLista rails-brRuby Inside (.com e .com.br)Working With Rails

Introdução ao Ruby on Rails > Ruby on Rails > Comunidade

Page 41: Introdução ao Ruby on Rails

And so much moreInternacionalização (i18n)RotasCacheAjaxBackground Jobs...

Introdução ao Ruby on Rails > Ruby on Rails > And so much more

Page 42: Introdução ao Ruby on Rails

Fim

Introdução ao Ruby on Rails > Fim