Slide 1

Slide 1 text

github.com/britto João Britto twitter.com/noteu

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

RS on Rails 2013 Ruby Além dos Trilhos

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

Slide 6

Slide 6 text

A dynamic, open source programming language with a focus on simplicity and productivity. It has an elegant syntax that is natural to read and easy to write.

Slide 7

Slide 7 text

"RS on Rails? bah, que tri!".upcase #=> RS ON RAILS? BAH, QUE TRI!

Slide 8

Slide 8 text

class Integer # Check whether the integer is evenly divisible by the argument. # # 0.multiple_of?(0) #=> true # 6.multiple_of?(5) #=> false # 10.multiple_of?(2) #=> true def multiple_of?(number) number != 0 ? self % number == 0 : zero? end end

Slide 9

Slide 9 text

Monkey Patch

Slide 10

Slide 10 text

Freedom Patch

Slide 11

Slide 11 text

module I18NExtensions def t(options = {}) I18n.t self, options end end Symbol.send :include, I18NExtensions

Slide 12

Slide 12 text

# Sem monkey patch t :save # Com monkey patch :save.t

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end @author = Author.first # sem has_many through @author.authorships.collect { |a| a.book } # com has_many through @author.books

Slide 15

Slide 15 text

class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end @author = Author.first # sem has_many through @author.authorships.collect { |a| a.book } # com has_many through @author.books

Slide 16

Slide 16 text

class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end @author = Author.first # sem has_many through @author.authorships.collect { |a| a.book } # com has_many through @author.books

Slide 17

Slide 17 text

class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end @author = Author.first # sem has_many through @author.authorships.collect { |a| a.book } # com has_many through @author.books

Slide 18

Slide 18 text

class Author < ActiveRecord::Base has_many :authorships has_many :books, :through => :authorships end class Authorship < ActiveRecord::Base belongs_to :author belongs_to :book end @author = Author.first # sem has_many through @author.authorships.collect { |a| a.book } # com has_many through @author.books

Slide 19

Slide 19 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 20

Slide 20 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 21

Slide 21 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 22

Slide 22 text

Para o resgate “Metaprogramaçãozinha”

Slide 23

Slide 23 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base include ActiveRecordExtensions belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 24

Slide 24 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base include ActiveRecordExtensions belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 25

Slide 25 text

module ActiveRecordExtensions def self.included(base) base.extend ClassMethods end module ClassMethods def self.extended(base) class << base alias_method_chain :belongs_to, :through_option end end def belongs_to_with_through_option(association, options = {}) if options[:through] if self.reflect_on_all_associations.find { |a| a.macro == :belongs_to && a.name == options[:through] } define_method association do |*args| through_assoc = self.send(options[:through], *args) through_assoc && through_assoc.send(options[:source] || association, *args) end else raise ':through option in :belongs_to macro must be another valid :belongs_to association' end else belongs_to_without_through_option association, options end end end end

Slide 26

Slide 26 text

module ActiveRecordExtensions def self.included(base) base.extend ClassMethods end module ClassMethods def self.extended(base) class << base alias_method_chain :belongs_to, :through_option end end def belongs_to_with_through_option(association, options = {}) if options[:through] if self.reflect_on_all_associations.find { |a| a.macro == :belongs_to && a.name == options[:through] } define_method association do |*args| through_assoc = self.send(options[:through], *args) through_assoc && through_assoc.send(options[:source] || association, *args) end else raise ':through option in :belongs_to macro must be another valid :belongs_to association' end else belongs_to_without_through_option association, options end end end end

Slide 27

Slide 27 text

alias_method_chain :belongs_to, :through_option

Slide 28

Slide 28 text

module ActiveRecordExtensions def self.included(base) base.extend ClassMethods end module ClassMethods def self.extended(base) class << base alias_method_chain :belongs_to, :through_option end end def belongs_to_with_through_option(association, options = {}) if options[:through] if self.reflect_on_all_associations.find { |a| a.macro == :belongs_to && a.name == options[:through] } define_method association do |*args| through_assoc = self.send(options[:through], *args) through_assoc && through_assoc.send(options[:source] || association, *args) end else raise ':through option in :belongs_to macro must be another valid :belongs_to association' end else belongs_to_without_through_option association, options end end end end

Slide 29

Slide 29 text

module ActiveRecordExtensions def self.included(base) base.extend ClassMethods end module ClassMethods def self.extended(base) class << base alias_method_chain :belongs_to, :through_option end end def belongs_to_with_through_option(association, options = {}) if options[:through] if self.reflect_on_all_associations.find { |a| a.macro == :belongs_to && a.name == options[:through] } define_method association do |*args| through_assoc = self.send(options[:through], *args) through_assoc && through_assoc.send(options[:source] || association, *args) end else raise ':through option in :belongs_to macro must be another valid :belongs_to association' end else belongs_to_without_through_option association, options end end end end

Slide 30

Slide 30 text

def avatar user && user.avatar end

Slide 31

Slide 31 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base include ActiveRecordExtensions belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 32

Slide 32 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base include ActiveRecordExtensions belongs_to :user belongs_to :avatar, :through => :user end @user = User.first # sem through @profile.user.avatar # com through @profile.avatar

Slide 33

Slide 33 text

module ActiveRecordExtensions def self.included(base) base.extend ClassMethods end module ClassMethods def self.extended(base) class << base alias_method_chain :belongs_to, :through_option end end def belongs_to_with_through_option(association, options = {}) if options[:through] if self.reflect_on_all_associations.find { |a| a.macro == :belongs_to && a.name == options[:through] } define_method association do |*args| through_assoc = self.send(options[:through], *args) through_assoc && through_assoc.send(options[:source] || association, *args) end else raise ':through option in :belongs_to macro must be another valid :belongs_to association' end else belongs_to_without_through_option association, options end end end end

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

Antes de fazer Monkey Patch

Slide 36

Slide 36 text

Tenho alternativa?

Slide 37

Slide 37 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user delegate :avatar, :to => :user, :allow_nil => true end @user = User.first # sem delegate @profile.user.avatar # com delegate @profile.avatar

Slide 38

Slide 38 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user delegate :avatar, :to => :user, :allow_nil => true end @user = User.first # sem delegate @profile.user.avatar # com delegate @profile.avatar

Slide 39

Slide 39 text

class User < ActiveRecord::Base belongs_to :avatar end class Profile < ActiveRecord::Base belongs_to :user delegate :avatar, :to => :user, :allow_nil => true end @user = User.first # sem delegate @profile.user.avatar # com delegate @profile.avatar

Slide 40

Slide 40 text

Eu preciso mesmo dele?

Slide 41

Slide 41 text

# Sem monkey patch t :save # Com monkey patch :save.t

Slide 42

Slide 42 text

require 'will_paginate' module WillPaginate module ViewHelpers pagination_options[:previous_label] = :prev_label.t(:scope => :mislav_will_paginate) pagination_options[:next_label] = :next_label.t(:scope => :mislav_will_paginate) def page_entries_info(collection, options = {}) entry_name = options[:entry_name] || :record.t(:scope => :mislav_will_paginate) entries_name = options[:entries_name] || :records.t(:scope => :mislav_will_paginate) if collection.total_pages < 2 case collection.size when 0 :no_records.t( :entry_name => entry_name, :scope => [:mislav_will_paginate, :messages] ) when 1 :showing_1.t( :entry_name => entry_name, :scope => [:mislav_will_paginate, :messages] ) else :showing_all.t( :size => collection.size, :entries_name => entries_name, :scope => [:mislav_will_paginate, :messages] ) end else :showing.t( :entries_name => entries_name, :from => collection.offset + 1, :to => collection.offset + collection.length, :total => collection.total_entries, :scope => [:mislav_will_paginate, :messages] ) end end end end

Slide 43

Slide 43 text

Outras Bibliotecas

Slide 44

Slide 44 text

http://en.wikipedia.org/wiki/Adapter_pattern Adapter Pattern

Slide 45

Slide 45 text

Por que eu devo evitar?

Slide 46

Slide 46 text

Esconde comportamento

Slide 47

Slide 47 text

Modifica globalmente

Slide 48

Slide 48 text

Dificulta atualização

Slide 49

Slide 49 text

Complica os testes

Slide 50

Slide 50 text

Testes dão confiança para mudar o que for necessário

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

não faz tudo para você Rails

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

routes.rb

Slide 55

Slide 55 text

$ wc -l config/routes.rb 358 config/routes.rb

Slide 56

Slide 56 text

Controllers

Slide 57

Slide 57 text

No content

Slide 58

Slide 58 text

http://weblog.jamisbuck.org/2006/10/18/skinny- controller-fat-model Skinny Controller, Fat Model

Slide 59

Slide 59 text

class PeopleController < ActionController::Base def index @people = Person.find( :conditions => ["added_at > ? and deleted = ?", Time.now.utc, false], :order => "last_name, first_name") @people = @people.reject { |p| p.address.nil? } end end

Slide 60

Slide 60 text

class Person < ActiveRecord::Base def self.find_recent people = find( :conditions => ["added_at > ? and deleted = ?", Time.now.utc, false], :order => "last_name, first_name") people.reject { |p| p.address.nil? } end # ... end class PeopleController < ActionController::Base def index @people = Person.find_recent end end

Slide 61

Slide 61 text

class Person < ActiveRecord::Base def self.find_recent people = find( :conditions => ["added_at > ? and deleted = ?", Time.now.utc, false], :order => "last_name, first_name") people.reject { |p| p.address.nil? } end # ... end class PeopleController < ActionController::Base def index @people = Person.find_recent end end

Slide 62

Slide 62 text

Models

Slide 63

Slide 63 text

Fat Models também são problemáticos

Slide 64

Slide 64 text

Defina as responsabilidades

Slide 65

Slide 65 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) def balance_in_us_dollar if currency == :us_dollar amount elsif currency == :real amount * conversion_rate(:us_dollar, :real) end end def balance_in_real if currency == :real amount elsif currency == :us_dollar amount * conversion_rate(:real, :us_dollar) end end def conversion_rate(from, to) SomeWebservice.get(from, to) end end

Slide 66

Slide 66 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) def balance_in_us_dollar if currency == :us_dollar amount elsif currency == :real amount * conversion_rate(:us_dollar, :real) end end def balance_in_real if currency == :real amount elsif currency == :us_dollar amount * conversion_rate(:real, :us_dollar) end end def conversion_rate(from, to) SomeWebservice.get(from, to) end end

Slide 67

Slide 67 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) def balance_in_us_dollar if currency == :us_dollar amount elsif currency == :real amount * conversion_rate(:us_dollar, :real) end end def balance_in_real if currency == :real amount elsif currency == :us_dollar amount * conversion_rate(:real, :us_dollar) end end def conversion_rate(from, to) SomeWebservice.get(from, to) end end

Slide 68

Slide 68 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) def balance_in_us_dollar if currency == :us_dollar amount elsif currency == :real amount * conversion_rate(:us_dollar, :real) end end def balance_in_real if currency == :real amount elsif currency == :us_dollar amount * conversion_rate(:real, :us_dollar) end end def conversion_rate(from, to) SomeWebservice.get(from, to) end end

Slide 69

Slide 69 text

class Money def initialize(amount, currency) @amount, @currency = amount, currency end def convert_to_us_dollar if currency == :us_dollar @amount elsif currency == :real @amount * ConversionRate.rate(:real, :us_dollar) end end def convert_to_real if currency == :real @amount elsif @currency == :dollar @amount * ConversionRate.rate(:us_dollar, :real) end end end

Slide 70

Slide 70 text

class Money def initialize(amount, currency) @amount, @currency = amount, currency end def convert_to_us_dollar if currency == :us_dollar @amount elsif currency == :real @amount * ConversionRate.rate(:real, :us_dollar) end end def convert_to_real if currency == :real @amount elsif @currency == :dollar @amount * ConversionRate.rate(:us_dollar, :real) end end end

Slide 71

Slide 71 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) composed_of :balance, :class_name => Money, :mapping => %w(amount currency) end

Slide 72

Slide 72 text

class Account < ActiveRecord::Base validates_numericality_of :amount validates_inclusion_of :currency, :in => %w(us_dollar real) def balance @balance ||= Money.new(amount, currency) end def balance=(balance) self.amount = balance.amount self.currency = balance.currency end end http://blog.plataformatec.com.br/2012/06/about- the-composed_of-removal/

Slide 73

Slide 73 text

Evite callbacks e observers

Slide 74

Slide 74 text

class User < ActiveRecord::Base before_save :get_avatar after_save :create_repository end

Slide 75

Slide 75 text

class UserRegistration def register(user) get_avatar_for(user) user.save! create_repository_for(user) end end

Slide 76

Slide 76 text

$ find app/models -name '*.rb' | xargs wc -l | sort -r | head -4 7567 total 608 app/models/channel.rb 563 app/models/article.rb 477 app/models/video.rb

Slide 77

Slide 77 text

http://blog.codeclimate.com/blog/2012/10/17/7- ways-to-decompose-fat-activerecord-models/ Decomponha models obesos

Slide 78

Slide 78 text

Views

Slide 79

Slide 79 text

<% people = Person.find( :conditions => ["added_at > ? and deleted = ?", Time.now.utc, false], :order => "last_name, first_name") %> <% people.reject { |p| p.address.nil? }.each do |person| %>
"> <%= person.last_name %>, <%= person.first_name %> <%= (Date.today - person.birthdate) / 365 %>
<% end %>

Slide 80

Slide 80 text

class Person < ActiveRecord::Base # ... def name "#{last_name}, #{first_name}" end def age (Date.today - birthdate) / 365 end def pseudo_id new_record? ? "new" : id end end

Slide 81

Slide 81 text

<% @people.each do |person| %>
<%= person.name %> <%= person.age %>
<% end %>

Slide 82

Slide 82 text

Evite duplicação

Slide 83

Slide 83 text

render :partial => 'something_duplicated'

Slide 84

Slide 84 text

<%= some_helper %>

Slide 85

Slide 85 text

Muitos locals

Slide 86

Slide 86 text

render :partial => template_name, :locals => { :my_object => my_object, :options => options[:options].join(" "), :use_jquery => options[:use_jquery], :use_css => options[:use_css], :thumb => options[:thumb], :full => options[:full], :width => options[:width], :height => options[:height], :thumb_width => options[:thumb_width], :thumb_height => options[:thumb_height] }

Slide 87

Slide 87 text

Helpers que renderizam partials

Slide 88

Slide 88 text

def comment_form(comment, options = {}) # ... render :partial => '_comment_form', :locals => a_huge_amount_of_locals end

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

Tudo no ApplicationHelper

Slide 91

Slide 91 text

Boas práticas

Slide 92

Slide 92 text

SOLID http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod

Slide 93

Slide 93 text

http://amzn.to/Ea92g

Slide 94

Slide 94 text

http://amzn.to/dnn9Lt

Slide 95

Slide 95 text

http://amzn.to/1nga3P

Slide 96

Slide 96 text

O consumo excessivo de Patterns pode trazer danos à saúde. Use com moderação.

Slide 97

Slide 97 text

Conheça suas ferramentas

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

github.com/britto Obrigado! twitter.com/noteu

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

• http://www.guygray.org/2013/08/08/the-explanatory-power-of-monkeys-who-cheat/ • http://wall.alphacoders.com/by_sub_category.php?id=199692 • http://upload.wikimedia.org/wikipedia/commons/4/40/Railroad-Gyula-b.jpg • http://yorkdailypicture.blogspot.com.br/2012/01/full-steam-ahead.html • http://flic.kr/p/LJF71 • http://www.trainsim.com/vbts/showthread.php?299612-Free-Steam-Locomotive- Drawings • http://theredthread.org/2012/03/08/our-burmese-days/ • http://flic.kr/p/Hjt7G • http://tanfield-railway.blogspot.com.br/2011/09/loco-inspection-prep.html • http://www.ppconstructionsafety.com/newsdesk/2013/04/22/rail-maintenance-firms- err-on-worker-safety/ Créditos das imagens