• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Código Saudável => Programador Feliz - Rs on Rails 2010
 

Código Saudável => Programador Feliz - Rs on Rails 2010

on

  • 9,361 views

Palestra do Rs On Rails, na qual demos algumas dicas de boas práticas para manter seu código mais limpo e ter absoluto controle da sua aplicação em produção.

Palestra do Rs On Rails, na qual demos algumas dicas de boas práticas para manter seu código mais limpo e ter absoluto controle da sua aplicação em produção.

Statistics

Views

Total Views
9,361
Views on SlideShare
1,774
Embed Views
7,587

Actions

Likes
10
Downloads
0
Comments
0

11 Embeds 7,587

http://blog.plataformatec.com.br 6931
http://feeds.feedburner.com 598
http://translate.google.com 13
http://blog.plataformatec.com.br. 11
http://localhost:3000 10
http://translate.googleusercontent.com 10
http://twitter.com 4
http://aspspider.info 4
http://www.hanrss.com 3
http://localhost 2
http://feedproxy.google.com 1
More...

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Código Saudável => Programador Feliz - Rs on Rails 2010 Código Saudável => Programador Feliz - Rs on Rails 2010 Presentation Transcript

  • Código Saudável =>Programador Feliz
  • [~]$ whoami
  • @rlm ores
  • 1993-1995
  • Ruby
  • 2003-2004
  • Ruby on Rails
  • 2011 Text
  • Sua aplicação
  • ArquiteturaModelosProdução
  • MVC
  • Model View Controller
  • Model ControllerView View View View View
  • class ArticlesController < ActionController::Base def index if params[:user_id].blank? @articles = Article.all else @articles = current_user.articles end endend
  • ModelDeslogado Logado Controller Controller View View View View View View
  • class ArticlesController < ActionController::Base def index @articles = Article.all endendclass Users::ArticlesController < ActionContro... def index @articles = current_user.articles.all endend
  • class UsersControllers < ApplicationController def index @users = User.all endendclass Admin::UsersControllers < ApplicationCont...def index @users = User.all endend
  • DRY
  • module UsersIndex def index @users = User.all endendclass UsersController < ApplicationController include UsersIndexendclass Admin::UsersControllers < ApplicationController include UsersIndexend
  • module UsersIndex def index @users = User.all endendclass UsersController < ApplicationController include UsersIndexendclass Admin::UsersControllers < ApplicationController include UsersIndexend
  • Acoplamento XRepetição de código
  • “Every piece of knowledgemust have a single,unambiguous, authoritativerepresentation within asystem.” Pragmatic Programmer
  • Repeat code =Repeat Logic
  • Repeat code =Repeat Logic
  • Não economizar nonúmero de controllers
  • Cada Controller é uma lógica diferente
  • DRY não é economizar código, mas manter aslógicas em um lugar só
  • ArquiteturaModelosProdução
  • SkinnyController,Fat Model
  • OOP
  • Obese Models
  • MuitasDifícil Manter Responsabilidades DifícilBaixa Coesão Compreender
  • Sintoma #1 MuitaResponsabilidade
  • x
  • class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w( us_dollar euro (...)) def convert_to_us_dollar if currency == :us_dollar currency elsif currency == :euro currency * ConversionRate.rate(:dollar,:euro) (...) end end def convert_to_euro if currency == :euro currency elsif currency == :dollar currency * ConversionRate.rate(:euro,:dollar) (...) end endend
  • UML 1
  • composed_of
  • class Money def initialize(amount, currency) @amount, @currency = amount, currency end def convert_to_us_dollar if currency == :us_dollar @currency elsif currency == :euro @currency * ConversionRate.rate(:dollar,:euro) (...) end end def convert_to_euro if currency == :euro @currency elsif @currency == :dollar @currency * ConversionRate.rate(:euro,:dollar) (...) end end
  • class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w( us_dollareuro (...)) composed_of :balance, :class_name =>Money, :mapping => %w( amount currency)end
  • Mais fácil de manter Responsabilidades (e reutilizar!) divididas Mais simples de APIs menores compreender
  • Sintoma #2Lógicas repetidas
  • Lixeira
  • class Post < ActiveRecord::Base # (...) default_scope where(trashed: false) scope :trashed, where(trashed: true) def trash update_attribute :trashed, true endend
  • class Comment < ActiveRecord::Base # (...) default_scope where(trashed: false) scope :trashed, where(trashed: true) def trash update_attribute :trashed, true endend
  • DRY!
  • module Trashable extend ActiveSupport::Concern included do default_scope where(trashed: false) scope :trashed, where(trashed: true) end def trash update_attribute :trashed, true endend
  • class Post < ActiveRecord::Base include Trashableendclass Comment < ActiveRecord::Base include Trashableend
  • Sintoma #3 “Super Abstração”do Banco de Dados
  • Models retiram dados do BD
  • post.comments.sizepost.comments.countpost.comments.length
  • post.comments.count
  • SQL (0.3ms) SELECT COUNT(*) FROM `comments`WHERE (`comments`.post_id = 1)
  • post.comments.length
  • Comment Load (0.4ms) SELECT `comments`.* FROM`comments` WHERE (`comments`.post_id = 1)
  • post.comments.size
  • # File activerecord/lib/active_record/relation.rb, line 84def size loaded? ? @records.length : countend
  • Active Record é bom!Mas que de olho no banco!
  • <% comments.each do |comment| %> <% if comment.post %> (...) <% end %><% end %>
  • Comment Load (0.6ms) SELECT `comments`.* FROM `comments`Post Load (0.4ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` =1 LIMIT 1Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` =2 LIMIT 1(...)Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id` =99 LIMIT 1Post Load (0.2ms) SELECT `posts`.* FROM `posts` WHERE `posts`.`id`= 100 LIMIT 1
  • N+1
  • <% comments.each do |comment|%> <% if comment.post_id %> (...) <% end %><% end %>
  • Comment Load (0.6ms) SELECT `comments`.* FROM`comments`
  • @comments = Comment.all(:include => :post)
  • Comment Load (0.7ms) SELECT `comments`.* FROM`comments`Post Load (46.4ms) SELECT `posts`.* FROM `posts` WHERE(`posts`.`id` IN (1,2,(...),100))
  • Extrair funcionalidades dos modelos: Composed ofEliminar duplicação de lógicas ConcernFicar de olho nas Queries Query Reviewer
  • ArquiteturaModelosProdução
  • Um dia a hora chega ...
  • Checklist!
  • AnalyticsException noti erPerformance loggerMonitoramento de ServidorNota A no YSlowDeploy automatizadoBackup
  • Solução Open SourceSolução via “serviço”
  • Analytics
  • Exception Noti er
  • Performance Logger
  • Monitoramento de Servidor
  • Nota Ano YSlow
  • DeployAutomatizado
  • git pulltouch tmp/restart.txt
  • git pulljammittouch tmp/restart.txt
  • rake db:backupgit pullrake db:migratejammittouch tmp/restart.txt
  • ps aux | ... | kill ...rake db:backupgit pull(...) rake resque:(...)rake db:migratejammittouch tmp/restart.txt
  • ps aux | ... | kill ...rake db:backupgit pull(...) rake resque:(...)rake sphinx:rebuildrake db:migratejammit
  • Mais de uma máquina ?Rollback ?Múltiplos Ambientes
  • Backup!
  • Cron + RSync
  • Teste seu Backup!
  • Crie um padrão de qualidade !Invista tempo (ou $$ ) em melhorias !Faça e cumpra um checklist
  • Código bem feito +Aplicação bem monitorada=> Programador Mais Feliz!
  • Make it work (and writetests to ensure that)Make it awesome(with tests you know that it still works)if you need, make it fast
  • Rodrigo Flores blog.plataformatec.com @rlmflores Perguntas?
  • ID blog twitterRodrigo Flores blog.plataformatec.com @rlmflores Perguntas?
  • Créditos das ImagensLego tristehttp://www. ickr.com/photos/kalexanderson/5421517469/Parquímetro de Portugalhttp://weblog.savanne.be/423-youre-doing-it-wrong“Cafeteira”http://therei xedit.failblog.orgAirplanehttp://www. ickr.com/photos/irish yguy/2426063460/