Slide 1

Slide 1 text

❤
 
 Hello Minsk!
 
 ❤

Slide 2

Slide 2 text

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

Slide 3

Slide 3 text

Stickers

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

Architecture

Slide 7

Slide 7 text

No content

Slide 8

Slide 8 text

Why?

Slide 9

Slide 9 text

Trying to unify architecture ideas for hanami projects

Slide 10

Slide 10 text

Getting feedback

Slide 11

Slide 11 text

Problems

Slide 12

Slide 12 text

Management Performance Maintenance

Slide 13

Slide 13 text

Management Performance Maintenance

Slide 14

Slide 14 text

Clean code Good architecture Maintainable product Pretty code

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Clean code Good architecture Maintainable product Pretty code

Slide 17

Slide 17 text

What do we really want?

Slide 18

Slide 18 text

To add new features

Slide 19

Slide 19 text

Isolation Sequential logic No global state

Slide 20

Slide 20 text

Delete (refactoring) old code

Slide 21

Slide 21 text

Isolation Test coverage

Slide 22

Slide 22 text

Conclusions

Slide 23

Slide 23 text

Isolation Sequential logic No global state
 Test coverage

Slide 24

Slide 24 text

But we live in a real world

Slide 25

Slide 25 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, :pin_transaction_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_callback_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')

Slide 26

Slide 26 text

How can we improve the situation?

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

Abstraction Actions

Slide 29

Slide 29 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, :pin_transaction_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_callback_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')

Slide 30

Slide 30 text

MVC V and C MVC

Slide 31

Slide 31 text

Solutions?

Slide 32

Slide 32 text

Abstraction Functional (callable) objects

Slide 33

Slide 33 text

Services Interactors dry-transactions Operations Etc.

Slide 34

Slide 34 text

t.me/pepegramming

Slide 35

Slide 35 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 36

Slide 36 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 37

Slide 37 text

def call(params) FuncObject.new.call(params) do |m| m.successful? do |value| flash[:info] = INFO_MESSAGE redirect_to routes.tasks_path end m.failed? do |value| self.body = … end end end

Slide 38

Slide 38 text

Isolation

Slide 39

Slide 39 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 40

Slide 40 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 41

Slide 41 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 42

Slide 42 text

Logic sequence

Slide 43

Slide 43 text

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

Slide 44

Slide 44 text

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

Slide 45

Slide 45 text

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

Slide 46

Slide 46 text

No global state

Slide 47

Slide 47 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 48

Slide 48 text

Easy testing

Slide 49

Slide 49 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 50

Slide 50 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 51

Slide 51 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 52

Slide 52 text

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

Slide 53

Slide 53 text

But objects
 can call other objects

Slide 54

Slide 54 text

Actions Interactors Libs Objects (public) (private)

Slide 55

Slide 55 text

Problems

Slide 56

Slide 56 text

So many objects,
 how to manage it?

Slide 57

Slide 57 text

Long names for objects — like: 
 Interactors::CreateUserWithTask
 Interactors::Module::CreateUserWithTask
 Interactors::Module::Module::CreateUserWithTask

Slide 58

Slide 58 text

We have to initialize instances every time

Slide 59

Slide 59 text

Containers!

Slide 60

Slide 60 text

Abstraction Containers

Slide 61

Slide 61 text

Dry-container

Slide 62

Slide 62 text

When someone tries to sell me dry-rb

Slide 63

Slide 63 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 64

Slide 64 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 65

Slide 65 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 66

Slide 66 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 67

Slide 67 text

Pros Controlled global state
 (in one place) Memorizing instances Mocs for testing Resolving deps on booting project

Slide 68

Slide 68 text

t.me/pepegramming

Slide 69

Slide 69 text

But we can use it better!

Slide 70

Slide 70 text

Abstraction Dry-auto_inject

Slide 71

Slide 71 text

When someone tries to sell me dry-rb

Slide 72

Slide 72 text

Why?

Slide 73

Slide 73 text

Dependency injection on steroids

Slide 74

Slide 74 text

Import = Dry::AutoInject(Container)

Slide 75

Slide 75 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 76

Slide 76 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 77

Slide 77 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 78

Slide 78 text

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

Slide 79

Slide 79 text

Abstraction Models

Slide 80

Slide 80 text

MVC V and C MVC

Slide 81

Slide 81 text

What can we do with it?

Slide 82

Slide 82 text

No logic

Slide 83

Slide 83 text

No validations

Slide 84

Slide 84 text

Just save and load data

Slide 85

Slide 85 text

Query objects

Slide 86

Slide 86 text

Query objects Repositories

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

Changesets
 or
 Command pattern (?)

Slide 89

Slide 89 text

Drop callbacks

Slide 90

Slide 90 text

Sequential logic

Slide 91

Slide 91 text

Examples

Slide 92

Slide 92 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 93

Slide 93 text

No content

Slide 94

Slide 94 text

Abstraction Applications

Slide 95

Slide 95 text

Rails App #1 Model
 Services

Slide 96

Slide 96 text

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

Slide 97

Slide 97 text

Rails App #1 Rails App #2 Model
 Services

Slide 98

Slide 98 text

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

Slide 99

Slide 99 text

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

Slide 100

Slide 100 text

No content

Slide 101

Slide 101 text

App App App lib

Slide 102

Slide 102 text

App App App lib Shared between apps

Slide 103

Slide 103 text

No content

Slide 104

Slide 104 text

Actions Interactors Libs (public) (private)

Slide 105

Slide 105 text

Apps Interactors Libs (public) (private)

Slide 106

Slide 106 text

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

Slide 107

Slide 107 text

App App App lib One server instance

Slide 108

Slide 108 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 109

Slide 109 text

Problems?

Slide 110

Slide 110 text

Hard
 not to forgot
 about other apps

Slide 111

Slide 111 text

Sometimes
 you have to use
 another logic

Slide 112

Slide 112 text

No content

Slide 113

Slide 113 text

Warning: Advanced level You can build projects without it

Slide 114

Slide 114 text

Abstraction Domains

Slide 115

Slide 115 text

DDD

Slide 116

Slide 116 text

No content

Slide 117

Slide 117 text

Separate domains for different business values

Slide 118

Slide 118 text

Each domain isolated from others

Slide 119

Slide 119 text

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

Slide 120

Slide 120 text

cons hard to start so much files™

Slide 121

Slide 121 text

No content

Slide 122

Slide 122 text

http is a small part
 of system

Slide 123

Slide 123 text

No content

Slide 124

Slide 124 text

websockets rack background processing
 ETL
 …

Slide 125

Slide 125 text

They all use business logic

Slide 126

Slide 126 text

No content

Slide 127

Slide 127 text

System consists
 of the different events

Slide 128

Slide 128 text

No content

Slide 129

Slide 129 text

User created Post created User updated
 Payment added Order completed …

Slide 130

Slide 130 text

Abstraction Event Sourcing

Slide 131

Slide 131 text

No content

Slide 132

Slide 132 text

No content

Slide 133

Slide 133 text

No content

Slide 134

Slide 134 text

No content

Slide 135

Slide 135 text

Events

Slide 136

Slide 136 text

Event
 log

Slide 137

Slide 137 text

Event
 log

Slide 138

Slide 138 text

Event
 log

Slide 139

Slide 139 text

But we need to calculate all events for get current state

Slide 140

Slide 140 text

CQRS
 
 (Command Query Responsibility Segregation)

Slide 141

Slide 141 text

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

Slide 142

Slide 142 text

Event log

Slide 143

Slide 143 text

Event log SQL Elastic NoSql

Slide 144

Slide 144 text

Event log SQL Elastic NoSql Current State

Slide 145

Slide 145 text

Event log SQL Elastic NoSql Current State Current State

Slide 146

Slide 146 text

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

Slide 147

Slide 147 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 148

Slide 148 text

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

Slide 149

Slide 149 text

How to start to use it

Slide 150

Slide 150 text

No content

Slide 151

Slide 151 text

github.com/RailsEventStore/rails_event_store

Slide 152

Slide 152 text

hanami-events

Slide 153

Slide 153 text

Proof of concept

Slide 154

Slide 154 text

Just transport layer with event versions and types

Slide 155

Slide 155 text

Conclusions

Slide 156

Slide 156 text

Isolate it

Slide 157

Slide 157 text

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

Slide 158

Slide 158 text

Maintenance is important

Slide 159

Slide 159 text

github.com/davydovanton/hanami-architecture

Slide 160

Slide 160 text

t.me/pepegramming

Slide 161

Slide 161 text

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