• Like
  • Save
Código Saudável => Programador Feliz - Rs on Rails 2010
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

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

  • 9,122 views
Published

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.

Published in Technology , Business
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
9,122
On SlideShare
0
From Embeds
0
Number of Embeds
2

Actions

Shares
Downloads
0
Comments
0
Likes
10

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • \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

Transcript

  • 1. Código Saudável =>Programador Feliz
  • 2. [~]$ whoami
  • 3. @rlm ores
  • 4. 1993-1995
  • 5. Ruby
  • 6. 2003-2004
  • 7. Ruby on Rails
  • 8. 2011 Text
  • 9. Sua aplicação
  • 10. ArquiteturaModelosProdução
  • 11. MVC
  • 12. Model View Controller
  • 13. Model ControllerView View View View View
  • 14. class ArticlesController < ActionController::Base def index if params[:user_id].blank? @articles = Article.all else @articles = current_user.articles end endend
  • 15. ModelDeslogado Logado Controller Controller View View View View View View
  • 16. class ArticlesController < ActionController::Base def index @articles = Article.all endendclass Users::ArticlesController < ActionContro... def index @articles = current_user.articles.all endend
  • 17. class UsersControllers < ApplicationController def index @users = User.all endendclass Admin::UsersControllers < ApplicationCont...def index @users = User.all endend
  • 18. DRY
  • 19. module UsersIndex def index @users = User.all endendclass UsersController < ApplicationController include UsersIndexendclass Admin::UsersControllers < ApplicationController include UsersIndexend
  • 20. module UsersIndex def index @users = User.all endendclass UsersController < ApplicationController include UsersIndexendclass Admin::UsersControllers < ApplicationController include UsersIndexend
  • 21. Acoplamento XRepetição de código
  • 22. “Every piece of knowledgemust have a single,unambiguous, authoritativerepresentation within asystem.” Pragmatic Programmer
  • 23. Repeat code =Repeat Logic
  • 24. Repeat code =Repeat Logic
  • 25. Não economizar nonúmero de controllers
  • 26. Cada Controller é uma lógica diferente
  • 27. DRY não é economizar código, mas manter aslógicas em um lugar só
  • 28. ArquiteturaModelosProdução
  • 29. SkinnyController,Fat Model
  • 30. OOP
  • 31. Obese Models
  • 32. MuitasDifícil Manter Responsabilidades DifícilBaixa Coesão Compreender
  • 33. Sintoma #1 MuitaResponsabilidade
  • 34. x
  • 35. 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
  • 36. UML 1
  • 37. composed_of
  • 38. 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
  • 39. 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
  • 40. Mais fácil de manter Responsabilidades (e reutilizar!) divididas Mais simples de APIs menores compreender
  • 41. Sintoma #2Lógicas repetidas
  • 42. Lixeira
  • 43. class Post < ActiveRecord::Base # (...) default_scope where(trashed: false) scope :trashed, where(trashed: true) def trash update_attribute :trashed, true endend
  • 44. class Comment < ActiveRecord::Base # (...) default_scope where(trashed: false) scope :trashed, where(trashed: true) def trash update_attribute :trashed, true endend
  • 45. DRY!
  • 46. 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
  • 47. class Post < ActiveRecord::Base include Trashableendclass Comment < ActiveRecord::Base include Trashableend
  • 48. Sintoma #3 “Super Abstração”do Banco de Dados
  • 49. Models retiram dados do BD
  • 50. post.comments.sizepost.comments.countpost.comments.length
  • 51. post.comments.count
  • 52. SQL (0.3ms) SELECT COUNT(*) FROM `comments`WHERE (`comments`.post_id = 1)
  • 53. post.comments.length
  • 54. Comment Load (0.4ms) SELECT `comments`.* FROM`comments` WHERE (`comments`.post_id = 1)
  • 55. post.comments.size
  • 56. # File activerecord/lib/active_record/relation.rb, line 84def size loaded? ? @records.length : countend
  • 57. Active Record é bom!Mas que de olho no banco!
  • 58. <% comments.each do |comment| %> <% if comment.post %> (...) <% end %><% end %>
  • 59. 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
  • 60. N+1
  • 61. <% comments.each do |comment|%> <% if comment.post_id %> (...) <% end %><% end %>
  • 62. Comment Load (0.6ms) SELECT `comments`.* FROM`comments`
  • 63. @comments = Comment.all(:include => :post)
  • 64. Comment Load (0.7ms) SELECT `comments`.* FROM`comments`Post Load (46.4ms) SELECT `posts`.* FROM `posts` WHERE(`posts`.`id` IN (1,2,(...),100))
  • 65. Extrair funcionalidades dos modelos: Composed ofEliminar duplicação de lógicas ConcernFicar de olho nas Queries Query Reviewer
  • 66. ArquiteturaModelosProdução
  • 67. Um dia a hora chega ...
  • 68. Checklist!
  • 69. AnalyticsException noti erPerformance loggerMonitoramento de ServidorNota A no YSlowDeploy automatizadoBackup
  • 70. Solução Open SourceSolução via “serviço”
  • 71. Analytics
  • 72. Exception Noti er
  • 73. Performance Logger
  • 74. Monitoramento de Servidor
  • 75. Nota Ano YSlow
  • 76. DeployAutomatizado
  • 77. git pulltouch tmp/restart.txt
  • 78. git pulljammittouch tmp/restart.txt
  • 79. rake db:backupgit pullrake db:migratejammittouch tmp/restart.txt
  • 80. ps aux | ... | kill ...rake db:backupgit pull(...) rake resque:(...)rake db:migratejammittouch tmp/restart.txt
  • 81. ps aux | ... | kill ...rake db:backupgit pull(...) rake resque:(...)rake sphinx:rebuildrake db:migratejammit
  • 82. Mais de uma máquina ?Rollback ?Múltiplos Ambientes
  • 83. Backup!
  • 84. Cron + RSync
  • 85. Teste seu Backup!
  • 86. Crie um padrão de qualidade !Invista tempo (ou $$ ) em melhorias !Faça e cumpra um checklist
  • 87. Código bem feito +Aplicação bem monitorada=> Programador Mais Feliz!
  • 88. 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
  • 89. Rodrigo Flores blog.plataformatec.com @rlmflores Perguntas?
  • 90. ID blog twitterRodrigo Flores blog.plataformatec.com @rlmflores Perguntas?
  • 91. 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/