Slide 1

Slide 1 text

What's new in Rails 5? Karol Galanciak Full Stack Developer at Twitter: @Azdaroth Github: Azdaroth https://karolgalanciak.com

Slide 2

Slide 2 text

ActionCable

Slide 3

Slide 3 text

ActionCable • Integration of WebSockets with the rest of your application

Slide 4

Slide 4 text

ActionCable • Integration of WebSockets with the rest of your application • Both client-side and server-side tools

Slide 5

Slide 5 text

ActionCable - server-side

Slide 6

Slide 6 text

ActionCable - server-side • Connections - connection between consumer and the sever

Slide 7

Slide 7 text

ActionCable - server-side • Connections - connection between consumer and the sever • Authentication / authorization goes here

Slide 8

Slide 8 text

ActionCable - connections module ApplicationCable class Connection < ActionCable::Connection::Base identified_by :current_user def connect self.current_user = find_user! end private def find_user! User.find_by(id: cookies.signed[:user_id]) or raise UnauthorizedConnectionError end end end

Slide 9

Slide 9 text

ActionCable - server-side • Channels - endpoints where the actual logic happens (~ controllers)

Slide 10

Slide 10 text

ActionCable - channels class ChatChannel < ActionCable::Channel::Base def subscribed stream_from "chat_#{params[:room]}" end def receive(payload) ActionCable.server.broadcast("chat_#{params[:room]}", payload) end end

Slide 11

Slide 11 text

ActionCable - client-side

Slide 12

Slide 12 text

ActionCable - client-side //= require action_cable this.App || (this.App = {}); App.cable = ActionCable.createConsumer(); App.chatChannel = App.cable.subscriptions.create({ channel: "ChatChannel", room: "Rails Core" }, { received: function(data) { $(".chat").append("

" + data["sent_by"] + ": " + data["body"] + "

") } }); App.chatChannel.send({ sent_by: "DHH", body: "OMG, it works!" });

Slide 13

Slide 13 text

Rails API

Slide 14

Slide 14 text

Rails API • rails new rails_5_app --api

Slide 15

Slide 15 text

Rails API • rails new rails_5_app —api • ApplicationController inherits from ActionController::API • Modifies the generators (no views, helpers and assets)

Slide 16

Slide 16 text

Attributes API

Slide 17

Slide 17 text

Attributes API class Order < ActiveRecord::Base attribute :price_in_cents, :money attribute :description, :string, default: "Default description" attribute :ordered_at, :datetime, default: -> { Time.current } attribute :tags_not_backed_by_db, :string, array: true end class MoneyType < ActiveRecord::Type::Integer def deserialize(value) if value.to_s.include?("$") price_in_dollars = value.gsub(/\$/, "").to_d super(price_in_dollars * 100) else super end end end ActiveRecord::Type.register(:money, MoneyType)

Slide 18

Slide 18 text

Attributes API class Order < ActiveRecord::Base attribute :price_in_cents, :money attribute :description, :string, default: "Default description" attribute :ordered_at, :datetime, default: -> { Time.current } attribute :tags_not_backed_by_db, :string, array: true end order = Order.new order.price_in_cents = "$10.0" order.price_in_cents => 1000 order.description => "Default description" order.ordered_at => "2016-01-01 12:00:00 +0200" order.tags_not_backed_by_db = ["WhateverItTakes", "5%", "Rich Piana"] order.tags_not_backed_by_db => ["WhateverItTakes", "5%", "Rich Piana"]

Slide 19

Slide 19 text

Attributes API • custom types (requires #deserialize method for assigning values and #serialize when querying database)

Slide 20

Slide 20 text

Attributes API • custom types (requires #deserialize method for assigning values and #serialize when querying database) • attributes don’t need to be backed by database

Slide 21

Slide 21 text

Attributes API • custom types (requires #deserialize method for assigning values and #serialize when querying database) • attributes don’t need to be backed by database • supports dirty tracking

Slide 22

Slide 22 text

Class / module variables per thread • cattr_accessor / mattr_accessor - but per thread - thread_cattr_accessor / thread_mattr_accessor

Slide 23

Slide 23 text

Class / module variables per thread module OmgGlobal thread_mattr_accessor :current_user end class ApplicationController < ActionController::Base # Please, don't do it in real code! before_action :set_current_user_globally def set_current_user_globally OmgGlobal.current_user = current_user end end class Post < ActiveRecord::Base after_save :create_version private def create_version Version.create(model: self.class.to_s, attributes: attributes, who_did_it: OmgGlobal.current_user.id) end end

Slide 24

Slide 24 text

Assets silenced by default in development

Slide 25

Slide 25 text

Assets silenced by default in development • quite_assets gem

Slide 26

Slide 26 text

Assets silenced by default in development • quite_assets gem • No more garbage in logs

Slide 27

Slide 27 text

Assets silenced by default in development • quite_assets gem • No more garbage in logs Started GET "/assets/public/home.js?body=1" for 127.0.0.1 at 2016-09-27 19:31:46 +0200 Started GET "/assets/bootstrap/collapse.js?body=1" for 127.0.0.1 at 2016-09-27 19:32:04 +0200 Started GET "/assets/font-awesome/fontawesome-webfont.woff2?v=4.5.0" for 127.0.0.1 at 2016-09-27 19:32:04 +0200 Started GET "/assets/public/locales.js?body=1" for 127.0.0.1 at 2016-09-27 19:32:04 +0200

Slide 28

Slide 28 text

ApplicationRecord

Slide 29

Slide 29 text

ApplicationRecord • New base class for models

Slide 30

Slide 30 text

ApplicationRecord class ApplicationRecord < ActiveRecord::Base include SoftDelete self.abstract_class = true has_paper_trail end class User < ApplicationRecord end

Slide 31

Slide 31 text

Rendering outside controllers

Slide 32

Slide 32 text

Rendering outside controllers OrdersController.render(:show, assigns: { order: Order.find(order_id) })

Slide 33

Slide 33 text

Rendering outside controllers OrdersController.render(:show, assigns: { order: Order.find(order_id) }) OrdersController.render(:_order, assigns: { order: Order.find(order_id) })

Slide 34

Slide 34 text

Rake / Rails commands

Slide 35

Slide 35 text

Rake / Rails commands • All rails commands can be executed with rake and all rake commands can be executed with rails

Slide 36

Slide 36 text

Rake / Rails commands rails db:migrate rake routes | grep some_route -> rails routes -g some_route

Slide 37

Slide 37 text

Caching collections

Slide 38

Slide 38 text

Caching collections • ActiveRecord::Collection#cache_key

Slide 39

Slide 39 text

Caching collections posts.cache_key => "posts/query-c60f5cf40b4d0d6f492ea6961c43ceb6-100-20160927121435182129"

Slide 40

Slide 40 text

Caching collections <% cache(@posts) do %> <% @posts.each do |post| %>

<%= render post %>

<% end %> <% end %>

Slide 41

Slide 41 text

ActiveRecord no longer halts execution of the callbacks when returning false

Slide 42

Slide 42 text

ActiveRecord no longer halts execution of the callbacks when returning false class Product < ActiveRecord::Base before_save :set_availability_status def set_availability_status self.available = somehow_compute_availability_status_which_returns_false end end product.save! => ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved

Slide 43

Slide 43 text

ActiveRecord no longer halts execution of the callbacks when returning false class Product < ActiveRecord::Base before_save :set_availability_status def set_availability_status self.available = somehow_compute_availability_status_which_returns_false throw(:abort) end end

Slide 44

Slide 44 text

ActiveRecord no longer halts execution of the callbacks when returning false • configurable with ActiveSupport.halt_callback_chains_on_return_false

Slide 45

Slide 45 text

Belongs-to association required by default

Slide 46

Slide 46 text

Belongs-to association required by default class Comment < ApplicationRecord belongs_to :author end

Slide 47

Slide 47 text

Belongs-to association required by default class Comment < ApplicationRecord belongs_to :author, optional: true end

Slide 48

Slide 48 text

Belongs-to association required by default • Configurable with Rails.application.config.active_record.belongs_to_r equired_by_default

Slide 49

Slide 49 text

redirect_back method

Slide 50

Slide 50 text

redirect_back method class UsersController < ApplicationController def update user = find_user user.update(params[:user]) redirect_to :back end end

Slide 51

Slide 51 text

redirect_back method class UsersController < ApplicationController def update user = find_user user.update(params[:user]) redirect_back(fallback_location: root_path) end end

Slide 52

Slide 52 text

ActiveRecord::Base.Suppress

Slide 53

Slide 53 text

ActiveRecord::Base.Suppress

Slide 54

Slide 54 text

ActiveRecord::Base.Suppress class Comment < ApplicationRecord belongs_to :author has_many :notifications after_save :send_notification def publish! update!(published_at: Time.current) end private def send_notification notifications.create(message: content, author: author) end end

Slide 55

Slide 55 text

ActiveRecord::Base.Suppress class Comment < ApplicationRecord belongs_to :author has_many :notifications after_save :send_notification def publish! update!(published_at: Time.current) end def publish_without_notification! Notification.suppress do publish! end end private def send_notification notifications.create(message: content, author: author) end end

Slide 56

Slide 56 text

Left Outer Join Support

Slide 57

Slide 57 text

Left Outer Join Support User.left_outer_joins(:posts, :comments, :notifications) User.left_joins(:posts, :comments, :notifications)

Slide 58

Slide 58 text

Config for UUIDs as primary keys

Slide 59

Slide 59 text

Config for UUIDs as primary keys create_table :orders, id: :uuid do |t| end

Slide 60

Slide 60 text

Config for UUIDs as primary keys • Configurable with: config.active_record.primary_key = :uuid

Slide 61

Slide 61 text

Queue adapter configurable per job

Slide 62

Slide 62 text

Queue adapter configurable per job config.active_job.queue_adapter = :delayed_job

Slide 63

Slide 63 text

Queue adapter configurable per job class DoSomethingExpensiveInBackgroundJob < ActiveJob::Base self.queue_adapter = :sidekiq end

Slide 64

Slide 64 text

ApplicationJob base class

Slide 65

Slide 65 text

ApplicationJob base class class ApplicationJob < ActiveJob::Base end

Slide 66

Slide 66 text

Validation of multiple contexts

Slide 67

Slide 67 text

Validation of multiple contexts class User < ActiveRecord::Base validate :validate_confirmation_info, on: :confirmation validate :validate_updatable, on: :update end

Slide 68

Slide 68 text

Validation of multiple contexts • Before: user.valid?(:confirmation) && user.valid?(:update)

Slide 69

Slide 69 text

Validation of multiple contexts • Now: user.valid?([:confirmation, :update])

Slide 70

Slide 70 text

Additional details for validations

Slide 71

Slide 71 text

Additional details for validations comment = Comment.new comment.valid? => false comment.errors.messages => {content: ["can’t be blank"]} comment.errors.details => {content:=>[{error: :blank}]} comment.errors.add(:content, :too_short, "Content is too short") comment.errors.details => {content: [{error: :blank}, {error: :too_short}]}

Slide 72

Slide 72 text

Saving records without timestamp update

Slide 73

Slide 73 text

Saving records without timestamp update user = User.first user.save(touch: false)

Slide 74

Slide 74 text

Bidirectional destroy

Slide 75

Slide 75 text

Bidirectional destroy • Doesn’t cause SystemStackError

Slide 76

Slide 76 text

Bidirectional destroy class Account < ActiveRecord::Base has_one :billing_address, dependent: :destroy end class BillingAddress < ActiveRecord::Base belongs_to :account, dependent: :destroy end

Slide 77

Slide 77 text

ActiveModel::AttributesAssi gnment

Slide 78

Slide 78 text

ActiveModel::AttributesAssi gnment class UserForm include ActiveModel::AttributeAssignment attr_accessor :email, :password, :password_confirmation end form = UserForm.new form.assign_attributes(email: "[email protected]")

Slide 79

Slide 79 text

ActionController::Parameters is not a HashWithIndifferentAccess

Slide 80

Slide 80 text

ActionController::Parameters is not a HashWithIndifferentAccess • Gotcha: def to_h if permitted? @parameters.to_h else slice(*self.class.always_permitted_parameters).permit!.to_h end end

Slide 81

Slide 81 text

ActionController::Parameters is not a HashWithIndifferentAccess • Gotcha: def to_h if permitted? @parameters.to_h else slice(*self.class.always_permitted_parameters).permit!.to_h end end def user_params params.permit!.to_h end def user_params params.to_unsafe_h end

Slide 82

Slide 82 text

Comments in migrations

Slide 83

Slide 83 text

Comments in migrations class CreateOrders < ActiveRecord::Migration[5.0] def change create_table :orders, comment: "Orders table" do |t| t.string :description, comment: "Description of the order" t.integer :owner_id, comment: "Owner of the order" t.timestamps end add_index :orders, :owner_id, name: "index_name", comment: "Index for owner_id" end end

Slide 84

Slide 84 text

Comments in migrations ActiveRecord::Schema.define(version: 20160928091043) do create_table "orders", force: :cascade, comment: "Orders table" do |t| t.string "description", comment: "Description of the order" t.integer "owner_id", comment: "Owner of the order" t.index ["owner_id"], name: "index_name",using: :btree, comment: "Index for owner_id" end end

Slide 85

Slide 85 text

Updating collection with callbacks and validations

Slide 86

Slide 86 text

Updating collection with callbacks and validations • ActiveRecord::Relation.update_all doesn’t trigger validations and callbacks

Slide 87

Slide 87 text

Updating collection with callbacks and validations • ActiveRecord::Relation.update_all doesn’t trigger validations and callbacks • But new ActiveRecord::Relation.update does ;)

Slide 88

Slide 88 text

Updating collection with callbacks and validations • ActiveRecord::Relation.update_all doesn’t trigger validations and callbacks • But new ActiveRecord::Relation.update does ;) Comment.limit(10).update(content: "")

Slide 89

Slide 89 text

Expression indexes

Slide 90

Slide 90 text

Expression indexes Author.where("lower(fullname) = ?", fullname.to_s.downcase)

Slide 91

Slide 91 text

Expression indexes add_index :authors, "lower(fullname)"

Slide 92

Slide 92 text

Indexed errors for nested attributes

Slide 93

Slide 93 text

Indexed errors for nested attributes class Invoice < ApplicationRecord has_many :items accepts_nested_attributes_for :items end class Item < ApplicationRecord validates :description, presence: true end > invoice = Invoice.new > item_1 = Item.new(description: "$$$$") > item_2 = Item.new > invoice.items = [item_1, item_2] > invoice.save > invoice.error.messages => {:"items.description"=>["can't be blank"]}

Slide 94

Slide 94 text

Indexed errors for nested attributes class Invoice < ApplicationRecord has_many :items, index_errors: true accepts_nested_attributes_for :items end class Item < ApplicationRecord validates :description, presence: true end >> invoice = Invoice.new >> item_1 = Item.new(description: "$$$$") >> item_2 = Item.new >> invoice.items = [item_1, item_2] >> invoice.save >> invoice.error.messages => {:"items[1].description"=>["can’t be blank"]}

Slide 95

Slide 95 text

Indexed errors for nested attributes • Configurable with config.active_record.index_nested_attribute_errors

Slide 96

Slide 96 text

No more ambiguous columns errors

Slide 97

Slide 97 text

No more ambiguous columns errors class Post < ApplicationRecord belongs_to :author has_many :comments end class Comment < ApplicationRecord belongs_to :author belongs_to :post end Post.joins(:comments).group(:author_id).count

Slide 98

Slide 98 text

New option for find_in_batches: finish

Slide 99

Slide 99 text

New option for find_in_batches: finish Comment.find_in_batches(start: 1001, finish: 10000, batch_size: 1000) do |group| group.each { |comment| do_some_stuff_with_comment(comment) } end

Slide 100

Slide 100 text

OR support in queries

Slide 101

Slide 101 text

OR support in queries

Slide 102

Slide 102 text

OR support in queries Article.where(author_name: "DHH").or(Article.where(category_name: "Basecamp"))

Slide 103

Slide 103 text

Acceptance validations works properly ;)

Slide 104

Slide 104 text

Acceptance validations works properly ;) • Problem: validates_acceptance_of accepts only "1" as truthy value

Slide 105

Slide 105 text

Acceptance validations works properly ;) • Problem: validates_acceptance_of accepts only "1" as truthy value • Now it supports both "1" and true

Slide 106

Slide 106 text

Acceptance validations works properly ;)

Slide 107

Slide 107 text

Acceptance validations works properly ;) • Bonus: configurable values

Slide 108

Slide 108 text

Acceptance validations works properly ;) • Bonus: configurable values class Comment < ActiveRecord::Base validates_acceptance_of :agreement, accept: [true, "y", "yes", "1", 1, "Rails"] end

Slide 109

Slide 109 text

fields_for accepts lambdas for child_index

Slide 110

Slide 110 text

fields_for accepts lambdas for child_index • My first Rails contribution ;)

Slide 111

Slide 111 text

fields_for accepts lambdas for child_index • My first Rails contribution ;) <%= f.simple_fields_for :items, item, child_index: -> { Time.current.to_i } do |builder| %> <% end %>

Slide 112

Slide 112 text

fields_for accepts lambdas for child_index • My first Rails contribution ;) <%= f.simple_fields_for :items, item, child_index: -> { Time.current.to_i } do |builder| %> <% end %> ''