Slide 1

Slide 1 text

-> [email protected] title: RubyKaigi2k18

Slide 2

Slide 2 text

❤
 
 Hello Japan!
 
 ❤

Slide 3

Slide 3 text

What have I learned here?

Slide 4

Slide 4 text

Is ramen still awesome?

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

Is Java more popular than ruby?

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Is Ruby still dying?

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

Is RubyKaigi still awesome?

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

❤
 
 Hello RubyKaigi!
 
 ❤

Slide 13

Slide 13 text

Anton Davydov github.com/davydovanton
 twitter.com/anton_davydov davydovanton.com

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

Stickers

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

~200 slides

Slide 18

Slide 18 text

-> [email protected] title: RubyKaigi2k18

Slide 19

Slide 19 text

Architecture

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

Why?

Slide 22

Slide 22 text

Trying to unify architecture ideas for hanami projects

Slide 23

Slide 23 text

Getting feedback

Slide 24

Slide 24 text

Problems

Slide 25

Slide 25 text

Management Performance Maintenance

Slide 26

Slide 26 text

Management Performance Maintenance

Slide 27

Slide 27 text

Clean code Good architecture Maintainable product Pretty code

Slide 28

Slide 28 text

Clean code Good architecture Maintainable product Pretty code biased view

Slide 29

Slide 29 text

What do we really want?

Slide 30

Slide 30 text

To add new features

Slide 31

Slide 31 text

Isolation Sequential logic No global state

Slide 32

Slide 32 text

Delete (refactoring) old code

Slide 33

Slide 33 text

Isolation Test coverage

Slide 34

Slide 34 text

Conclusions

Slide 35

Slide 35 text

Isolation Sequential logic No global state
 Test coverage

Slide 36

Slide 36 text

But we live in a real world

Slide 37

Slide 37 text

class InstitutionsController < ApplicationController load_and_authorize_resource :only => [:destroy,:edit,:new,:create,:update] before_filter :authenticate_user!, :except => [:student_registration, :show, :validate_registration_pin, :result, :admission, :buy_registration_pin,:paygate_callback_failure, :paygate_cancel, :paygate_pending, :paygate_callback_success, :pi nsaction_info_print] before_filter :find_institution, :except => [:show,:index, :new, :create, :semesters_for_institute_type, :start_end_date_for_assessment_period, :courses_for_batch, :paygate_callback_failure, :paygate_cancel, :paygate_pending, :paygate_cal _success, :pin_transaction_info_print] before_filter :add_bread_crumb,:except => [:show] def paygate_callback_success @pay_gate_config = YAML::load(File.open("#{Rails.root}/config/pay_gate_config.yml"))[Rails.env] @payment = TransactionRecord.find_by_order_number(params[:OrderID]) uri = URI("https://fidelitypaygate.fidelitybankplc.com/cipg/MerchantServices/UpayTransactionStatus.ashx") parameters = {:MERCHANT_ID => "#{@pay_gate_config['merchant_id']}", :ORDER_ID => "#{@payment.order_number}"} uri.query = URI.encode_www_form(parameters) result =open(uri).read result_hash = Hash.from_xml(result) record_payment_details(result_hash) if result_hash["CIPG"]["StatusCode"] == PaymentRecord::PAYMENT_SUCCESS_CODE if @payment.transactionable_type.eql?("PaymentRecord") redirect_to institution_fees_path(@payment.transactionable_type.fee.institution), :notice => "Payment transaction has been #{result_hash['CIPG']['Status']}" elsif @payment.transactionable_type.eql?("PinBuyerInfo") unless @payment.transactionable.pin_id.present? @registration = @payment.transactionable.registration @valid_registration_pin_groups = @registration.valid_registration_pin_groups @online_valid_registration_pin_groups = @valid_registration_pin_groups.where(:pin_available_type => 'Online') @offline_valid_registration_pin_groups = @valid_registration_pin_groups.where(:pin_available_type => 'Offline') @available_pin = nil @online_valid_registration_pin_groups.each do |vpg| if vpg.available_pins.present? @available_pin = vpg.available_pins.first break else next end end if !@available_pin.present? @offline_valid_registration_pin_groups.each do |vpg| if vpg.available_pins.present? @available_pin = vpg.available_pins.first break else next end end end if @available_pin.present? @payment.transactionable.pin_id = @available_pin.id @payment.transactionable.save @available_pin.is_available = false @available_pin.save @available_pin.reload if @available_pin.pin_group.pin_available_type == 'Offline' @message = "Your Order Number is #{@payment.order_number}. Please Print Transaction report to claim you PIN from Institution." else @assigned_pin = @available_pin.number @message = "Your PIN is #{@assigned_pin}. Please keep this PIN secret." end else @message = "No pin available for #{@registration.name}. Your order number is #{@payment.order_number}.Please contact with institution to get your money back if you have paid." end else pin = Pin.find @payment.transactionable.pin_id if(pin.present? && pin.pin_group.pin_available_type == 'Offline') @message = "Your Order Number is #{@payment.order_number}. Please Print Transaction report to claim you PIN from Institution." else @available_pin = Pin.find @payment.transactionable.pin_id @assigned_pin = @available_pin.number @message = "Your PIN is #{ @assigned_pin}. Please keep this PIN secret."

Slide 38

Slide 38 text

How can we improve the situation?

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

Abstraction Actions

Slide 41

Slide 41 text

class InstitutionsController < ApplicationController load_and_authorize_resource :only => [:destroy,:edit,:new,:create,:update] before_filter :authenticate_user!, :except => [:student_registration, :show, :validate_registration_pin, :result, :admission, :buy_registration_pin,:paygate_callback_failure, :paygate_cancel, :paygate_pending, :paygate_callback_success, :pi nsaction_info_print] before_filter :find_institution, :except => [:show,:index, :new, :create, :semesters_for_institute_type, :start_end_date_for_assessment_period, :courses_for_batch, :paygate_callback_failure, :paygate_cancel, :paygate_pending, :paygate_cal _success, :pin_transaction_info_print] before_filter :add_bread_crumb,:except => [:show] def paygate_callback_success @pay_gate_config = YAML::load(File.open("#{Rails.root}/config/pay_gate_config.yml"))[Rails.env] @payment = TransactionRecord.find_by_order_number(params[:OrderID]) uri = URI("https://fidelitypaygate.fidelitybankplc.com/cipg/MerchantServices/UpayTransactionStatus.ashx") parameters = {:MERCHANT_ID => "#{@pay_gate_config['merchant_id']}", :ORDER_ID => "#{@payment.order_number}"} uri.query = URI.encode_www_form(parameters) result =open(uri).read result_hash = Hash.from_xml(result) record_payment_details(result_hash) if result_hash["CIPG"]["StatusCode"] == PaymentRecord::PAYMENT_SUCCESS_CODE if @payment.transactionable_type.eql?("PaymentRecord") redirect_to institution_fees_path(@payment.transactionable_type.fee.institution), :notice => "Payment transaction has been #{result_hash['CIPG']['Status']}" elsif @payment.transactionable_type.eql?("PinBuyerInfo") unless @payment.transactionable.pin_id.present? @registration = @payment.transactionable.registration @valid_registration_pin_groups = @registration.valid_registration_pin_groups @online_valid_registration_pin_groups = @valid_registration_pin_groups.where(:pin_available_type => 'Online') @offline_valid_registration_pin_groups = @valid_registration_pin_groups.where(:pin_available_type => 'Offline') @available_pin = nil @online_valid_registration_pin_groups.each do |vpg| if vpg.available_pins.present? @available_pin = vpg.available_pins.first break else next end end if !@available_pin.present? @offline_valid_registration_pin_groups.each do |vpg| if vpg.available_pins.present? @available_pin = vpg.available_pins.first break else next end end end if @available_pin.present? @payment.transactionable.pin_id = @available_pin.id @payment.transactionable.save @available_pin.is_available = false @available_pin.save @available_pin.reload if @available_pin.pin_group.pin_available_type == 'Offline' @message = "Your Order Number is #{@payment.order_number}. Please Print Transaction report to claim you PIN from Institution." else @assigned_pin = @available_pin.number @message = "Your PIN is #{@assigned_pin}. Please keep this PIN secret." end else @message = "No pin available for #{@registration.name}. Your order number is #{@payment.order_number}.Please contact with institution to get your money back if you have paid." end else pin = Pin.find @payment.transactionable.pin_id if(pin.present? && pin.pin_group.pin_available_type == 'Offline') @message = "Your Order Number is #{@payment.order_number}. Please Print Transaction report to claim you PIN from Institution." else @available_pin = Pin.find @payment.transactionable.pin_id @assigned_pin = @available_pin.number

Slide 42

Slide 42 text

MVC V and C MVC

Slide 43

Slide 43 text

Solutions?

Slide 44

Slide 44 text

Abstraction Functional (callable) objects

Slide 45

Slide 45 text

Services Interactors dry-transactions dry-monads (DO notations) Operations Etc.

Slide 46

Slide 46 text

func_object = FuncObject.new func_object.call(params) # => result object with state

Slide 47

Slide 47 text

func_object = FuncObject.new func_object.call(params) # => result object with state

Slide 48

Slide 48 text

func_object = FuncObject.new func_object.call(params) # => result object

Slide 49

Slide 49 text

Isolation

Slide 50

Slide 50 text

def call(params) result = FuncObject.new.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 51

Slide 51 text

def call(params) result = FuncObject.new.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 52

Slide 52 text

def call(params) result = FuncObject.new.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 53

Slide 53 text

Logic sequence

Slide 54

Slide 54 text

class Create include Dry::Transaction include Dry::Matcher Dry::Validation.load_extensions(:monads) VALIDATOR = Dry::Validation.JSON do # ... end step :extract step :validate step :create

Slide 55

Slide 55 text

class Create include Dry::Transaction include Dry::Matcher Dry::Validation.load_extensions(:monads) VALIDATOR = Dry::Validation.JSON do # ... end step :extract step :validate step :create

Slide 56

Slide 56 text

class Interactor def call(payload) data = yield extract!(payload) entity = yield validate!(data) create!(entity) end # … end

Slide 57

Slide 57 text

class Interactor def call(payload) extract! validate! create! end # … end

Slide 58

Slide 58 text

No global state

Slide 59

Slide 59 text

def call(params) result = FuncObject.new.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 60

Slide 60 text

Easy testing

Slide 61

Slide 61 text

def initialize(object: FuncObject.new) @object = object end def call(params) result = @object.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 62

Slide 62 text

def initialize(object: FuncObject.new) @object = object end def call(params) result = @object.call(params) if result.successful? flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end Dependency Injection ❤

Slide 63

Slide 63 text

let(:action) { Create.new(object: SuccessObject.new) } it { expect(action.call(params).to eq ... }
 
 let(:action) { Create.new(object: FailedObject.new) } it { expect(action.call(params).to eq ... }

Slide 64

Slide 64 text

let(:other_object) { -> (_) { nil } }
 let(:object) { Create.new(object: other_object) } it { expect(action.call(params).to eq ... }

Slide 65

Slide 65 text

Objects can call other objects

Slide 66

Slide 66 text

Actions Interactors Libs Objects (public) (private)

Slide 67

Slide 67 text

Problems

Slide 68

Slide 68 text

So many objects,
 how to manage it?

Slide 69

Slide 69 text

Long names for objects — like: 
 Interactors::CreateUserWithTask
 Interactors::Module::CreateUserWithTask
 Interactors::Module::Module::CreateUserWithTask
 Orders::Current::Coupons::Operations::Apply

Slide 70

Slide 70 text

We have to initialize instances every time

Slide 71

Slide 71 text

Containers!

Slide 72

Slide 72 text

Abstraction Containers

Slide 73

Slide 73 text

Dry-container

Slide 74

Slide 74 text

When someone tries to sell me dry-rb

Slide 75

Slide 75 text

Container = Dry::Container.new Container.register('interactors.create_user', Interactors::CreateUser.new) Container['interactors.create_user'] # => Interactors::CreateUser instance Container['interactors.create_user'].call(...)

Slide 76

Slide 76 text

Container = Dry::Container.new Container.register('interactors.create_user', Interactors::CreateUser.new) Container['interactors.create_user'] # => Interactors::CreateUser instance Container['interactors.create_user'].call(...)

Slide 77

Slide 77 text

Container = Dry::Container.new Container.register('interactors.create_user', Interactors::CreateUser.new) Container['interactors.create_user'] # => Interactors::CreateUser instance Container['interactors.create_user'].call(...)

Slide 78

Slide 78 text

def call(params) result = Container['interactors.create_user'].call(params) if result[:successful] flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 79

Slide 79 text

Pros • Controlled global state (in one place) • Memorizing instances • Mocs for testing

Slide 80

Slide 80 text

But we can use it better!

Slide 81

Slide 81 text

Abstraction Dry-auto_inject

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

Why?

Slide 84

Slide 84 text

Dependency injection on steroids

Slide 85

Slide 85 text

Import = Dry::AutoInject(Container)

Slide 86

Slide 86 text

include Import[‘interactors.create_user']
 
 def call(params) result = create_user.call(params) if result[:successful] flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 87

Slide 87 text

include Import[‘interactors.create_user']
 
 def call(params) result = create_user.call(params) if result[:successful] flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end Dependency Injection ❤

Slide 88

Slide 88 text

include Import[‘interactors.create_user']
 
 def call(params) result = create_user.call(params) if result[:successful] flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path else self.body = … end end

Slide 89

Slide 89 text

let(:action) { Create.new(create_user: MockObject.new) } it { expect(action.call(params).to eq ... }

Slide 90

Slide 90 text

Abstraction Models

Slide 91

Slide 91 text

MVC V and C MVC

Slide 92

Slide 92 text

What can we do with it?

Slide 93

Slide 93 text

No logic

Slide 94

Slide 94 text

No validations

Slide 95

Slide 95 text

Just save and load data

Slide 96

Slide 96 text

Query objects

Slide 97

Slide 97 text

Query objects Repositories

Slide 98

Slide 98 text

No content

Slide 99

Slide 99 text

Changesets
 or
 Command pattern (?)

Slide 100

Slide 100 text

Drop callbacks

Slide 101

Slide 101 text

Sequential logic

Slide 102

Slide 102 text

Examples

Slide 103

Slide 103 text

class CreateUser include Import['repos.user_repo'] def call(payload) user_repo.create(payload.merge(created_on: Date.today end end CreateUser.new.call(user_data)

Slide 104

Slide 104 text

No content

Slide 105

Slide 105 text

Abstraction Applications

Slide 106

Slide 106 text

Rails App #1 Model
 Services

Slide 107

Slide 107 text

Rails App #2 Model
 Services Rails App #1 Model
 Services

Slide 108

Slide 108 text

Rails App #1 Rails App #2 Model
 Services

Slide 109

Slide 109 text

Rails App #1 Rails App #2 Model
 Services Rails App #3 Model
 Services

Slide 110

Slide 110 text

Rails App #1 Rails App #3 Rails App #2 Model
 Services

Slide 111

Slide 111 text

No content

Slide 112

Slide 112 text

App App App lib

Slide 113

Slide 113 text

App App App lib Shared between apps

Slide 114

Slide 114 text

No content

Slide 115

Slide 115 text

Actions Interactors Libs (public) (private)

Slide 116

Slide 116 text

Apps Interactors Libs (public) (private)

Slide 117

Slide 117 text

web
 admin #1
 admin #2 ==> business
 api logic
 mobile

Slide 118

Slide 118 text

App App App lib One server instance

Slide 119

Slide 119 text

App App App lib One server instance App App App lib App App App lib App App App lib App App App lib App App App lib App App App lib App App App lib

Slide 120

Slide 120 text

Problems?

Slide 121

Slide 121 text

Hard not to forgot
 about other apps

Slide 122

Slide 122 text

Sometimes
 you have to use
 another logic

Slide 123

Slide 123 text

No content

Slide 124

Slide 124 text

Warning: Advanced level You can build projects without it

Slide 125

Slide 125 text

Abstraction dry-system

Slide 126

Slide 126 text

Dependency management system

Slide 127

Slide 127 text

Auto register dependency to container

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

No content

Slide 130

Slide 130 text

No content

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

Dependency booting

Slide 133

Slide 133 text

No content

Slide 134

Slide 134 text

Abstraction Domains

Slide 135

Slide 135 text

DDD

Slide 136

Slide 136 text

No content

Slide 137

Slide 137 text

No content

Slide 138

Slide 138 text

Separate domains for different business values

Slide 139

Slide 139 text

Each domain isolated from others

Slide 140

Slide 140 text

pros easy to create separated services: just replace code domains + containers = ❤

Slide 141

Slide 141 text

cons hard to start so much files™

Slide 142

Slide 142 text

No content

Slide 143

Slide 143 text

http is a small part
 of system

Slide 144

Slide 144 text

No content

Slide 145

Slide 145 text

websockets rack background processing
 ETL
 …

Slide 146

Slide 146 text

They all use business logic

Slide 147

Slide 147 text

No content

Slide 148

Slide 148 text

System consists
 of the different events
 (Event Storming)

Slide 149

Slide 149 text

No content

Slide 150

Slide 150 text

User created Post created User updated
 Payment added Order completed …

Slide 151

Slide 151 text

Abstraction Event Sourcing

Slide 152

Slide 152 text

No content

Slide 153

Slide 153 text

No content

Slide 154

Slide 154 text

No content

Slide 155

Slide 155 text

Events

Slide 156

Slide 156 text

Event
 log

Slide 157

Slide 157 text

Event
 log

Slide 158

Slide 158 text

Event
 log

Slide 159

Slide 159 text

No content

Slide 160

Slide 160 text

No content

Slide 161

Slide 161 text

No content

Slide 162

Slide 162 text

But we need to calculate all events for get current state

Slide 163

Slide 163 text

CQRS
 
 (Command Query Responsibility Segregation)

Slide 164

Slide 164 text

– Martin Fowler “You can use a different model to update information than the model you use to read information”

Slide 165

Slide 165 text

Event log

Slide 166

Slide 166 text

Event log SQL Elastic NoSql

Slide 167

Slide 167 text

Event log SQL Elastic NoSql Current State

Slide 168

Slide 168 text

Event log SQL Elastic NoSql Current State Current State

Slide 169

Slide 169 text

Event log SQL Elastic NoSql Current State Current State Ap Ap Ap lib Ap Ap Ap lib

Slide 170

Slide 170 text

Pros • Each service isolated • All processing is in the background • Easy to add instances for service • Can be written on any language and you can call it from any app • Persistance

Slide 171

Slide 171 text

Cons • Not a silver bullet • Hard to understand the whole chain of events • Complicated • Another architecture type
 with different DB structure • Not popular in ruby

Slide 172

Slide 172 text

How to start to use it

Slide 173

Slide 173 text

No content

Slide 174

Slide 174 text

github.com/RailsEventStore/ rails_event_store

Slide 175

Slide 175 text

github.com/zilverline/sequent

Slide 176

Slide 176 text

hanami-events

Slide 177

Slide 177 text

Proof of concept

Slide 178

Slide 178 text

Just pub sub transport layer with event versions and types

Slide 179

Slide 179 text

Not only rails and hanami

Slide 180

Slide 180 text

Event Sourcing

Slide 181

Slide 181 text

Conclusions

Slide 182

Slide 182 text

Isolate it

Slide 183

Slide 183 text

Don’t use anything
 having no idea
 why do you need it

Slide 184

Slide 184 text

Maintenance is important

Slide 185

Slide 185 text

github.com/davydovanton/ hanami-architecture

Slide 186

Slide 186 text

github.com/davydovanton/ cookie_box

Slide 187

Slide 187 text

git.io/vFxl1

Slide 188

Slide 188 text

-> [email protected] title: RubyKaigi2k18

Slide 189

Slide 189 text

github.com/davydovanton
 twitter.com/anton_davydov davydovanton.com Thank you ❤