Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building Maintainable Rails Apps

Building Maintainable Rails Apps

This talk was given at RubyC in Kiev in June 2016.

The video for this talk is here: http://andypike.com/blog/conferences/rubyc-2016/

We love Rails! When the project is young we move at light speed! As time moves on, code entangles and development slows. In this talk we will explore why this happens and ways you can avoid it. You will learn a different “Rails Way” that retains what we love and adds good object orientated design which makes your app easier to maintain. We will see how to implement form objects, service objects and presenters in a Rails app to separate responsibilities and aid maintainability. If your Rails app is hard to maintain or you would like to learn techniques to avoid it, this talk is for you.

196ab25f16dcfd37518a41ceb15e0da0?s=128

Andy Pike

June 04, 2016
Tweet

Transcript

  1. Building Maintainable Rails Apps @andypike

  2. None
  3. Thank you!

  4. Charlie

  5. Allow myself to introduce… …myself

  6. Andy Pike

  7. Rails Core Team Ruby Core Team RSpec Core Team

  8. Any Core Team

  9. None
  10. Awesome Famous Inc.

  11. I’m a freelance developer You can hire me I can

    totally 100% help you You can hire me!
  12. You can follow me: (You can also hire me!) @andypike

  13. None
  14. None
  15. Basic Visual Basic C++ Classic ASP .NET Rails PHP

  16. $ rails new awesome_project

  17. None
  18. None
  19. None
  20. None
  21. None
  22. “Programmers at work maintaining a Ruby on Rails application” classicprogrammerpaintings.com

  23. ∞ Light speed Fast Medium Slow Age of project Time

    to develop a feature Heat death of the universe
  24. Why?

  25. None
  26. Skinny Controller

  27. Fat Model

  28. Fat Controller

  29. Obese Model

  30. What would DHH do?

  31. None
  32. None
  33. How do we improve things?

  34. Single Responsibility Principle A class should have one, and only

    one, reason to change.
  35. Entry point HTTP Run appropriate logic Controllers

  36. Data Persistence Associations Closely related logic Models

  37. Generate markup from data Views

  38. Where does the other code go?

  39. Dealing with input Business Logic Database Queries UI Logic Rails

    is Missing Constructs For: ȴ 
  40. andypike / rectify

  41. Form Objects Command Objects Query Objects Presenter Objects Rectify Provides:

    ȴ 
  42. Contrived Examples Use of imagination required WARNING

  43. Dealing with input Business Logic UI Logic Database Queries ȴ

  44. Context

  45. class UsersController < ApplicationController def new @user = User.new end

    def create @user = User.new(user_params) if @user.save redirect_to dashboard_path else render :new end end private def user_params params.require(:user).permit(:first_name, :last_name, :email) end end
  46. class User < ActiveRecord::Base has_many :things validates :email, :presence =>

    true end
  47. def update @user = User.find(params[:id]) if @user.update(update_user_params) redirect_to dashboard_path else

    render :edit end end private def create_user_params params.require(:user).permit(:first_name, :last_name, :email) end def update_user_params params.require(:user).permit(:first_name, :last_name, :email, :age) end
  48. class User < ActiveRecord::Base has_many :things validates :email, :presence =>

    true validates :age, :presence => true, :if => :persisted? end
  49. def update @user = User.find(params[:id]) user_params = current_user.admin? ? admin_user_params

    : update_user_params if @user.update(user_params) redirect_to dashboard_path else render :edit end end private # def create_user_params # def update_user_params def admin_user_params params.require(:user).permit(:first_name, :last_name, :email, :age, :role) end
  50. Context Whitelisted attributes and validations are in different places.

  51. Context Increases Complexity

  52. Structure

  53. = simple_form_for @company do |f| = f.input :name = f.simple_fields_for

    :users_attributes, @user do |u| = u.input :full_name = u.input :email = f.submit "Sign Up"
  54. class Company < ActiveRecord::Base has_many :users accepts_nested_attributes_for :users end class

    User < ActiveRecord::Base belongs_to :company def full_name [first_name, last_name].join(" ") end def full_name=(name) names = name.split(" ", 2) self.first_name = names.first self.last_name = names.last end end
  55. Structure Forms matching the database structure

  56. Types

  57. { "utf8" => "✓", "authenticity_token" => "gjsQSQXchsBI7yuz…", "user" => {

    "full_name" => "Andy Pike", "age" => "25" }, "commit" => "Save", "id" => "1" } 2016 - params[:user][:age] # => TypeError: String can't be coerced into Fixnum
  58. Types Param values are Strings

  59. Introducing: Form Objects

  60. Deals with input data Whitelists parameters Validations Indirection from models

    Type coercion
  61. class RegisterUserForm < Rectify::Form attribute :first_name, String attribute :last_name, String

    attribute :email, String validates :email, :presence => true end class UpdateProfileForm < Rectify::Form attribute :first_name, String attribute :last_name, String attribute :email, String attribute :age, Integer validates :email, :presence => true validates :age, :presence => true end
  62. class RegisterForm < Rectify::Form attribute :company_name, String attribute :full_name, String

    attribute :email, String validates :email, :presence => true def first_name name_parts.first end def last_name name_parts.last end private def name_parts full_name.split(" ", 2) end end
  63. = simple_form_for @company do |f| = f.input :name = f.simple_fields_for

    :users_attributes, @user do |u| = u.input :full_name = u.input :email = f.submit "Sign Up" # vs = simple_form_for @form do |f| = f.input :company_name = f.input :full_name = f.input :email = f.submit "Sign Up"
  64. def new @form = RegisterUserForm.new end def create @form =

    RegisterUserForm.from_params(params) if @form.valid? # Do something interesting else render :new end end # no strong_parameters :o)
  65. def edit user = User.find(params[:id]) @form = UpdateProfileForm.from_model(user) end def

    update @form = UpdateProfileForm.from_params(params) # @form.first_name => "Andy Pike" # @form.age => 25 # @form.attributes => { :first_name => "Andy Pike" ... } if @form.valid? # Do something interesting else render :edit end end
  66. class AccountHolderForm < UserForm attribute :age, Integer attribute :colours, Array

    attribute :address, AddressForm attribute :contacts, Array[ContactForm] end @form = AccountHolderForm.from_params(params) @form.valid? # validates the form, superclass, # nested forms and array of forms
  67. None
  68. Business Logic ȴ Dealing with input UI Logic Database Queries

  69. Where does it go? ȴ

  70. In the controller? ȴ

  71. UserMailer.confirmation(@user).deliver_later case @user.potential_revenue when :low logger.info("We don’t care about #{@user.full_name}")

    when :medium CRM.add(@user) when :high CRM.add(@user) SMS.notify_sales_high_value_customer(@user) end redirect_to dashboard_path else render :new end end ȴ def create @user = User.new(user_params) if @user.save
  72. Controller Not HTTP Not the controller’s concern ȴ

  73. In the model? ȴ

  74. def create @user = User.new(user_params) if @user.register redirect_to dashboard_path else

    render :new end end ȴ
  75. class User def register if save UserMailer.confirmation(self).deliver_later case potential_revenue when

    :low logger.info("We don’t care about #{full_name}") when :medium CRM.add(self) when :high CRM.add(self) SMS.notify_sales_high_value_customer(self) end end persisted? end end ȴ
  76. class User def register return false unless save send_confirmation send("#{potential_revenue}_potential_revenue")

    true end def send_confirmation UserMailer.confirmation(self).deliver_later end def low_potential_revenue def medium_potential_revenue def high_potential_revenue end ȴ
  77. ȴ

  78. Model Leads to God Objects Harder to understand Too many

    responsibilities ȴ
  79. Service Objects ȴ

  80. class UserService def self.register(params) # stuff end # every other

    method moved # from the user model end ȴ
  81. ȴ

  82. (Misunderstood) Service Objects Ends up being a replacement for the

    model ȴ
  83. Introducing: Command Objects ȴ

  84. Encapsulate a business task Named using Verbs Called by the

    Controller Multiple results No callbacks ȴ
  85. class RegisterUser < Rectify::Command def initialize(form) @form = form end

    def call return broadcast(:invalid) if @form.invalid? # Your code goes here broadcast(:ok) end private # def do_something # end end ȴ
  86. def create @form = RegisterUserForm.from_params(params) RegisterUser.call(@form) do on(:ok) { redirect_to

    dashboard_path } on(:invalid) { render :new } end end ȴ
  87. class PlaceOrder < Rectify::Command def initialize(form, customer) @form = form

    @customer = customer end def call return broadcast(:invalid) if @form.invalid? return broadcast(:card_expired) if card_expired? transaction do order = create_order update_crm notify_customer broadcast(:ok, order) end end private def create_order ȴ
  88. def create @form = OrderForm.from_params(params) PlaceOrder.call(@form, current_user) do on(:ok) {

    |order| redirect_to order_path(order) } on(:invalid) { render :new } on(:card_expired) { redirect_to billing_path } end end ȴ
  89. ȴ

  90. Business Logic Dealing with input UI Logic Database Queries ȴ

  91. WAT? 

  92. class UsersController < ApplicationController def index @users = User.where(:plays_minecraft =>

    true) end def show @user = User.find(params[:id]) @recent_orders = @user.orders.where("created_at > ?", 5.days.ago) end end 
  93. class User < ActiveRecord::Base has_many :orders scope :cool, -> {

    where(:plays_minecraft => true) } def recent_orders orders.where("created_at > ?", 5.days.ago) end end 
  94. def self.programmer_admins important_value = some_logic_required_by_the_query active .admin .programmer .where("SOME SQL

    ?", important_value) .where("SOME MORE REALLY LONG COMPLEX SQL") .where("SOME MORE REALLY REALLY LONG COMPLEX SQL") .order(:created_at => :desc) end def self.some_logic_required_by_the_query # Involved calculations end 
  95. def self.important_orders sql = <<-SQL.strip_heredoc WITH regional_sales AS ( SELECT

    region, SUM(amount) AS total_sales FROM orders GROUP BY region ), top_regions AS ( SELECT region FROM regional_sales WHERE total_sales > (SELECT SUM(total_sales)/10 FROM regional_sales) ) SELECT region, product, SUM(quantity) AS product_units, SUM(amount) AS product_sales FROM orders WHERE region IN (SELECT region FROM top_regions) AND amount > :amount GROUP BY region, product; SQL Order.find_by_sql([sql, { :amount => 50 }]) end 
  96. Queries in the Model Can lead to large models Harder

    to understand 
  97. Introducing: Query Objects 

  98. Encapsulates a database query and logic required to build it

  99. class CoolUsers < Rectify::Query def query User.where(:plays_minecraft => true) end

    end # Usage: CoolUsers.new.count CoolUsers.new.first CoolUsers.new.exists? CoolUsers.new.none? CoolUsers.new.to_a CoolUsers.new.map(&:age) # All Enumerable methods CoolUsers.new.each do |user| puts user.name end 
  100. class UsersOlderThan < Rectify::Query def initialize(age) @age = age end

    def query User.where("age > ?", @age) end end UsersOlderThan.new(25).count 
  101. class UsersWithBlacklistedEmail < Rectify::Query def initialize(blacklist) @blacklist = blacklist end

    def query User.where(:email => blacklisted_emails) end private def blacklisted_emails @blacklist.map { |b| b.email.strip.downcase } end end 
  102. active_users_over_20 = ActiveUsers.new | UsersOlderThan.new(20) active_users_over_20 = ActiveUsers.new.merge(UsersOlderThan.new(20)) active_users_over_20 =

    Rectify::Query.merge( ActiveUsers.new, UsersOlderThan.new(20) ) active_users_over_20.count 
  103. class UsersOverUsingSql < Rectify::Query include Rectify::SqlQuery def initialize(age) @age =

    age end def model User end def sql <<-SQL.strip_heredoc SELECT * FROM users WHERE age > :age ORDER BY age ASC SQL end def params { :age => @age } end end 
  104. UI Logic Business Logic Dealing with input Database Queries ȴ

  105. Views

  106. <% 8.upto(22) do |hour| %> <div class="timestamp"><%= "#{hour.to_s.rjust(2, '0')}:00" %></div>

    <% end %>
  107. Helpers

  108. module ApplicationHelper def hours 8.upto(22) do |hour| time = "#{hour.to_s.rjust(2,

    '0')}:00" content_tag(:div, time, :class => "timestamp") end end end <%= hours %>
  109. <% if current_user.admin? && current_user.company.plan.paid? %> <%= link_to "#{current_user.company.name} Billing",

    account_path %> <% end %>
  110. module ApplicationHelper def billing_link return unless current_user.admin? && current_user.company.plan.paid? link_to

    "#{current_user.company.name} Billing", account_path end end <div> <%= billing_link %> </div>
  111. Introducing: Presenter Objects

  112. Encapsulates view logic Full page or component

  113. class CalendarPresenter < Rectify::Presenter def hours 8.upto(22) do |hour| yield

    formatted_time(hour) end end private def formatted_time(hour) "#{hour.to_s.rjust(2, '0')}:00" end end
  114. class CalendarController < ApplicationController include Rectify::ControllerHelpers def show present CalendarPresenter.new

    end end <% presenter.hours do |hour| %> <div class="timestamp"><%= hour %></div> <% end %>
  115. class BillingPresenter < Rectify::Presenter attribute :user, User def billing_link return

    unless show_billing? link_to "#{user.company.name} Billing", account_path end private def show_billing? user.admin? && user.company.plan.paid? end end
  116. class AccountsController < ApplicationController include Rectify::ControllerHelpers def show present BillingPresenter.new(:user

    => current_user) end end <div> <%= presenter.billing_link %> </div>
  117. def show present BillingPresenter.new(:user => current_user) present MenuPresenter.new, :for =>

    :menu present FooterPresenter.new, :for => :footer end <nav><%= presenter(:menu).login_link %></nav> <div><%= presenter.billing_link %></div> <footer> <%= presenter(:footer).copyright_notice %> </footer>
  118. None
  119. Testing

  120. RSpec Setup # spec/rails_helper.rb require "rectify/rspec" RSpec.configure do |config| config.include

    Rectify::RSpec::Helpers end
  121. Testing Forms RSpec.describe UserForm do subject { described_class.new(:name => "Andy")

    } it "is valid with valid attributes" do expect(subject).to be_valid end describe "#name" do it "cannot be blank" do subject.name = "" expect(subject).to be_invalid end end end
  122. Stubbing Forms form = stub_form(:valid? => true, :name => "Andy")

    form.valid? # => true form.invalid? # => false form.name # => "Andy" form.attributes # => { :name => "Andy" } # or form = Rectify::StubForm.new(:valid? => true, :name => “Andy")
  123. Testing Commands ȴ RSpec.describe PlaceOrder do context "when the form

    is valid" do it "broadcasts :ok" do form = stub_form(:valid? => true) command = described_class.new(form) expect { command.call }.to broadcast(:ok) end end end
  124. Testing Queries  RSpec.describe UsersOlderThan do it "returns users older

    than the supplied age" do older = create(:user, :age => 10) younger = create(:user, :age => 8) expect(UsersOlderThan.new(9).to_a).to match_array([older]) end end
  125. Stubbing Queries  it "returns the only user's age" do

    stub_query(AllUsers, :results => User.new(:age => 25)) expect(subject.total_ages).to eq(25) end it "returns the sum of all users ages" do stub_query(AllUsers, :results => [ User.new(:age => 25), User.new(:age => 20) ]) expect(subject.total_ages).to eq(45) end
  126. Testing Presenters it "renders the billing link" do presenter =

    BillingPresenter.new(:user => admin_user) expect(presenter.billing_link).to eq('<a href="/billing">Billing</a>') end it "renders the billing link for current_user” do presenter = BillingPresenter.new presenter.attach_controller(ApplicationController) # use current_user expect(presenter.billing_link).to eq('<a href="/billing">Billing</a>') end
  127. What’s the point of all this?

  128. Avoid controllers and models growing to an unmanageable size and

    complexity
  129. None
  130. pragmatic /praɡˈmatɪk/ adjective dealing with things sensibly and realistically in

    a way that is based on practical rather than theoretical considerations.
  131. ∞ Light speed Fast Medium Slow Age of project Time

    to develop a feature Interesting point
  132. None
  133. None
  134. Tweet me questions or catch up with me later Don’t

    forget, you can hire me! @andypike