Slide 1

Slide 1 text

fat models MUST DIE @arkham @steffoz

Slide 2

Slide 2 text

let’s talk about Rails

Slide 3

Slide 3 text

Model View Controller

Slide 4

Slide 4 text

Skinny controller, fat model

Slide 5

Slide 5 text

$ wc -l app/models/* | sort -rn | sed -n '2,4p' 625 app/models/activity.rb 407 app/models/task.rb 364 app/models/user.rb

Slide 6

Slide 6 text

Owners Of our application business logic

Slide 7

Slide 7 text

Knows too much or does too much God Object

Slide 8

Slide 8 text

Is it wrong?

Slide 9

Slide 9 text

Software Design

Slide 10

Slide 10 text

Robert C. Martin Uncle Bob © Mike Clark

Slide 11

Slide 11 text

Two values of software

Slide 12

Slide 12 text

Software meets the current needs of the current user 2nd value

Slide 13

Slide 13 text

wait,

Slide 14

Slide 14 text

Software is easy to change 1st value

Slide 15

Slide 15 text

Agile

Slide 16

Slide 16 text

SOLID Principles

Slide 17

Slide 17 text

Single Responsibility Principle

Slide 18

Slide 18 text

SRP Every class should have a single responsibility, and that responsibility should be entirely encapsulated by the class.

Slide 19

Slide 19 text

A class should have one, and only one, reason to change SRP

Slide 20

Slide 20 text

let’s talk about Rails (again)

Slide 21

Slide 21 text

ActiveRecord::Base Persist and represent DB rows

Slide 22

Slide 22 text

Control HTTP requests/ responses at high level ActionController::Base

Slide 23

Slide 23 text

Where do we put business logic?

Slide 24

Slide 24 text

ActiveSupport::Concern

Slide 25

Slide 25 text

require 'active_support/concern' module NameGreeter extend ActiveSupport::Concern included do attr_accessor :name end def greet puts "Hi! I'm #{name}!" end module ClassMethods def build(name) self.new.tap do |instance| instance.name = name end end end end class User include NameGreeter end user = User.build("Mark") user.greet >> “Hi! I’m Mark!”

Slide 26

Slide 26 text

class Document < ActiveRecord::Base include Taggable include Visible include Dropboxed include Omasake end

Slide 27

Slide 27 text

app/models/concerns app/controllers/concerns Rails 4

Slide 28

Slide 28 text

Logic separation

Slide 29

Slide 29 text

Code reuse

Slide 30

Slide 30 text

Rails Drama

Slide 31

Slide 31 text

Models are still God Objects! Runtime

Slide 32

Slide 32 text

class User include NameGreeter end User.ancestors.include? NameGreeter >> true

Slide 33

Slide 33 text

Mixins are a form of Inheritance

Slide 34

Slide 34 text

Gang of Four Favor object composition to class inheritance

Slide 35

Slide 35 text

is-a Inheritance has-a Composition A cat is a pet A cat has a tail

Slide 36

Slide 36 text

Easier to change

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

OOP in RUBY

Slide 40

Slide 40 text

OOP I did it again

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

We need to calculate stats about football matches Scenario

Slide 44

Slide 44 text

class Match < ActiveRecord::Base def first_half_win? fh_made > fh_taken end def second_half_win? sh_made > sh_taken end def first_half_loss?; ... ; end def second_half_loss?; ... ; end def first_half_draw?; ... ; end def second_half_draw?; ... ; end end

Slide 45

Slide 45 text

Value Object

Slide 46

Slide 46 text

Equality is dependent on their value rather than an identity Property

Slide 47

Slide 47 text

class Score < Struct.new(:goals_made, :goals_taken) def win? goals_made > goals_taken end def draw? goals_made == goals_taken end def loss? goals_made < goals_taken end end

Slide 48

Slide 48 text

class Match < ActiveRecord::Base def first_half_score Score.new(fh_made, fh_taken) end def second_half_score Score.new(sh_made, sh_taken) end end

Slide 49

Slide 49 text

Struct #hash #eql?

Slide 50

Slide 50 text

We are closing an e- commerce purchase using Order, Customer and Product objects Scenario

Slide 51

Slide 51 text

Action is complex

Slide 52

Slide 52 text

Action reaches across multiple models

Slide 53

Slide 53 text

Action interacts with external services

Slide 54

Slide 54 text

Command Object a.k.a. Services

Slide 55

Slide 55 text

class ItemsController < ApplicationController def add_to_cart item = Item.find(params[:id]) AddToCart.new(current_user, item).execute! end end

Slide 56

Slide 56 text

class AddToCart < Struct.new(:user, :item) def execute! cart.add_item!(item) end private def cart user.active_cart end end

Slide 57

Slide 57 text

Encapsulate all the logic for a specific scenario

Slide 58

Slide 58 text

Reuse logic in multiple contexts

Slide 59

Slide 59 text

Filter events by full-text search, distance and category Scenario

Slide 60

Slide 60 text

class EventsController < ApplicationController def index @events = Event.published if params[:lat] && params[:lng] && params[:distance] @events = @events.near(lat, lng, distance) end if params[:query].present? @events = @events.matching(params[:query]) end if params[:category_id].present? @events = @events.in_category(params[:category_id]) end end end

Slide 61

Slide 61 text

Query Object

Slide 62

Slide 62 text

Responsible for returning a result set based on business rules Purpose

Slide 63

Slide 63 text

class EventsQuery < OpenStruct def scope(scope = Events.scoped) scope = scope.published if lat && lng && distance scope = scope.near(lat, lng, distance) end if query.present? scope = scope.matching(query) end if category_id.present? scope = scope.of_category(category_id) end scope end end

Slide 64

Slide 64 text

class EventsController < ApplicationController def index @events = EventsQuery.new(params[:query]).scope end end

Slide 65

Slide 65 text

DRY up your views

Slide 66

Slide 66 text

class EventsQuery < OpenStruct include ActiveModel::Conversion extend ActiveModel::Naming def persisted? false end # ... end

Slide 67

Slide 67 text

<%= form_for @query, as: :query, url: events_path, method: :get do |f| %> <%= f.text_field :query %> <% # ... %> <% end %>

Slide 68

Slide 68 text

Send mail notifications after the creation of new comments Scenario

Slide 69

Slide 69 text

class Comment < ActiveRecord::Base after_create :send_notification! private def send_notification! AppMailer.comment_submission(self).deliver end end

Slide 70

Slide 70 text

Model hooks are for data integrity

Slide 71

Slide 71 text

Do we always want notifications?

Slide 72

Slide 72 text

Command Object!

Slide 73

Slide 73 text

Decorator

Slide 74

Slide 74 text

Proxy

Slide 75

Slide 75 text

class CommentsController < ApplicationController def create @comment = Comment.new(params[:comment]) if @comment.save redirect_to blog_path, notice: "Comment was posted." else render "new" end end end

Slide 76

Slide 76 text

class CommentsController < ApplicationController def create @comment = Notifier.new(Comment.new(params[:comment])) if @comment.save redirect_to blog_path, notice: "Comment was posted." else render "new" end end end

Slide 77

Slide 77 text

class Notifier < Struct(:comment) def save comment.save && send_notification! end private def send_notification! AppMailer.comment_submission(comment).deliver true end end class Comment < ActiveRecord::Base end

Slide 78

Slide 78 text

Exhibit a.k.a. Presenter

Slide 79

Slide 79 text

The primary goal of exhibits is to insert a model object within a rendering context. Purpose

Slide 80

Slide 80 text

It’s a decorator Unrecognized messages are passed through to the underlying object

Slide 81

Slide 81 text

Augment models behaviour when it is needed

Slide 82

Slide 82 text

= link_to @user.full_name, @user = raw sanitize(@user.bio) = image_tag(@user.gravatar_url)

Slide 83

Slide 83 text

- user = UserPresenter.new(@user, self) = user.link_to = user.bio = user.gravatar

Slide 84

Slide 84 text

require 'delegate' class UserPresenter < SimpleDelegator def initialize(user, context) @context = context super(user) # Set up delegation end def gravatar_url md5 = Digest::MD5.hexdigest(email.downcase) "http://gravatar.com/avatar/#{md5}.png" end def gravatar @context.image_tag(gravatar_url) end end

Slide 85

Slide 85 text

Seamless integration

Slide 86

Slide 86 text

OOP alternative to Rails helpers

Slide 87

Slide 87 text

DCI Data, Context & Interaction

Slide 88

Slide 88 text

Separate what the system is (data) from what the system does (behaviour). Purpose

Slide 89

Slide 89 text

Use case

Slide 90

Slide 90 text

Context Roles

Slide 91

Slide 91 text

Transfer money between two accounts Scenario

Slide 92

Slide 92 text

class Account < Struct.new(:owner, :balance) end account = Account.new("Bob", 500.0)

Slide 93

Slide 93 text

bob_account = Account.new("Bob", 100.0) alice_account = Account.new("Alice", 50.0) context = MoneyTransferContext.new( bob_account, alice_account ) context.transfer(10.0) puts bob_account.amount # => 90.0 puts alice_account.amount # => 60.0

Slide 94

Slide 94 text

class MoneyTransferContext < Struct.new(:source, :destination) module SourceRole def withdraw(amount) self.balance -= amount end end module DestinationRole def deposit(amount) self.amount += amount end end end

Slide 95

Slide 95 text

#extend

Slide 96

Slide 96 text

bob_account = Account.new("Bob", 100.0) alice_account = Account.new("Alice", 50.0) bob_account.extend SourceRole bob_account.withdraw(amount) # => 90.0 alice_account.withdraw(amount) # NoMethodError: undefined method...

Slide 97

Slide 97 text

class MoneyTransferContext < Struct.new(:source, :destination) # ... def transfer(amount) source.extend SourceRole destination.extend DestinationRole source.withdraw(amount) destination.deposit(amount) end end

Slide 98

Slide 98 text

Domain model Use case Role Data Context Interaction

Slide 99

Slide 99 text

Give first-class status to system behavior

Slide 100

Slide 100 text

Improved spatial locality

Slide 101

Slide 101 text

ENOUGH.

Slide 102

Slide 102 text

Recap

Slide 103

Slide 103 text

Rails is great!

Slide 104

Slide 104 text

MVC/ActiveRecord cannot solve everything

Slide 105

Slide 105 text

When in doubt, Composition is your ally

Slide 106

Slide 106 text

Don’t be afraid of new objects

Slide 107

Slide 107 text

Think of Rails as a dependency

Slide 108

Slide 108 text

Whatever works best in your domain!

Slide 109

Slide 109 text

Sandi Metz Practical Object Oriented Design in Ruby © Sebastian Delmont

Slide 110

Slide 110 text

Classes can be no longer than one hundred lines of code. 1st rule

Slide 111

Slide 111 text

Methods can be no longer than five lines of code. 2nd rule

Slide 112

Slide 112 text

Pass no more than four parameters into a method. Hash options are parameters. 3rd rule

Slide 113

Slide 113 text

Controllers can instantiate only one object. 4th rule

Slide 114

Slide 114 text

It’s tough, but rewarding!

Slide 115

Slide 115 text

Questions! @arkham @steffoz http://workshop.welaika.com