Layered Design for Ruby on Rails Applications - Vladimir Dementyev - E-Book

Layered Design for Ruby on Rails Applications E-Book

Vladimir Dementyev

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

The Ruby on Rails framework boosts productivity by leveraging the convention-over-configuration principle and model-view-controller (MVC) pattern, enabling developers to build features efficiently. This initial simplicity often leads to complexity, making a well-structured codebase difficult to maintain. Written by a seasoned software engineer and award-winning contributor to many other open-source projects, including Ruby on Rails and Ruby, this book will help you keep your code maintainable while working on a Rails app.
You’ll get to grips with the framework’s capabilities and principles to harness the full potential of Rails, and tackle many common design problems by discovering useful patterns and abstraction layers. By implementing abstraction and dividing the application into manageable modules, you’ll be able to concentrate on specific parts of the app development without getting overwhelmed by the entire codebase. This also encourages code reuse, simplifying the process of adding new features and enhancing the application's capabilities. Additionally, you’ll explore further steps in scaling Rails codebase, such as service extractions.
By the end of this book, you’ll become a code design specialist with a deep understanding of the Rails framework principles.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 354

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Layered Design for Ruby on Rails Applications

Discover practical design patterns for maintainable web applications

Vladimir Dementyev

BIRMINGHAM—MUMBAI

Layered Design for Ruby on Rails Applications

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Rohit Rajkumar

Publishing Product Manager: Himani Dewan

Book Project Manager: Sonam Pandey

Content Development Editor: Abhishek Jadhav

Technical Editor: Simran Udasi

Copy Editor: Safis Editing

Proofreader: Safis Editing

Indexer: Rekha Nair

Production Designer: Joshua Misquitta

DevRel Marketing Coordinator: Nivedita Pandey

First published: September 2023

Production reference: 2280823

Packt Publishing Ltd

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK.

ISBN 978-1-80181-378-5

www.packtpub.com

To trains, train riders, and little train lovers.

– Vladimir Dementyev

Contributors

About the author

Vladimir Dementyev is a principal backend engineer at Evil Martians, a product development consultancy from Earth, focusing on building maintainable web applications and developers’ productivity. He is the creator of popular open source tools, such as AnyCable and TestProf, and a contributor to many other open source projects, including Ruby on Rails and Ruby itself. Vladimir plays an active role in the Ruby community through his code contributions and by speaking at conferences and sharing his passion for coding via articles and blog posts. For his contributions to the Ruby ecosystem, Vladimir was awarded the Fukuoka Ruby Award in 2021 and the Ruby Hero Russia Award in 2017.

I would like to thank my family, who support my extracurriculars, such as writing a book; the humans from Mars, and especially Phobos, for shaping my vision of how to write code; the Saint-P Ruby community for heated though well-argumented discussions; the MetroNorth and Amtrak trains for non-distracting writing environments; and the Peekskill Coffee House for the coffee and crepes that fueled Chapters 4, 8, and 12.

About the reviewer

Mahabub Islam is a seasoned software developer with a strong focus on Ruby on Rails and JavaScript. With six years of experience in the industry, he has honed his expertise in building robust and scalable web applications. Mahabub’s passion for clean code and efficient design led him to explore various design patterns and best practices, making him the perfect reviewer for the book Rails Design Patterns and Best Practices.

His in-depth knowledge of the framework, coupled with his experience in building complex applications, allows him to provide valuable insights and practical advice to developers seeking to optimize their Rails projects.

Table of Contents

Preface

Part 1: Exploring Rails and Its Abstractions

1

Rails as a Web Application Framework

Technical requirements

The journey of a click through Rails abstraction layers

From web requests to abstraction layers

Rack

Rails on Rack

Rails routing

C for controller

Beyond requests – background and scheduled tasks

The need for background jobs

Jobs as units of work

Scheduled jobs

The heart of a web application – the database

The trade-off between abstractions and database performance

Database-level abstractions

Summary

Questions

Exercises

Further reading

2

Active Models and Records

Technical requirements

Active Record overview – persistence and beyond

Object-relational mapping

From mapping to the model

From model to anything

Active Model – the hidden gem behind Active Record

Active Model as an interface

Active Model as an Active Record satellite

Active Model versus Struct – performance implications

Active Model for an Active Record-like experience

Seeking God objects

Summary

Questions

Exercises

Further reading

3

More Adapters, Less Implementations

Technical requirements

Active Job as a universal queue interface

Adapterizing queues

Serializing all things

Active Storage and its adapters and plugins

Adapters versus plugins

Adapters and wrappers at your service

Summary

Questions

Exercises

Further reading

4

Rails Anti-Patterns?

Technical requirements

Callbacks, callbacks everywhere

Callbacks under control (and in controllers)

Active Record callbacks go wild

Concerning Rails concerns

Extracting behavior, not code

Concerns are still modules, with all the shortcomings

Extracting objects from objects

On global and current states

Current everything

Summary

Questions

Exercises

5

When Rails Abstractions Are Not Enough

Technical requirements

The curse of fat/thin controllers and thin/fat models

From fat controllers to fat models

A fat controller example

Refactoring the example controller following the thin controllers, fat models principle

From fat models to services

Generic services and granular abstractions

Layered architecture and abstraction layers

Summary

Questions

Part 2: Extracting Layers from Models

6

Data Layer Abstractions

Technical requirements

Using query objects to extract (complex) queries from models

Extracting query objects

Scopes versus query objects

Reusable query objects and Arel

Code organization with query objects versus architecture layers

Separating domain and persistence with repositories

Summary

Questions

7

Handling User Input outside of Models

Technical requirements

Form objects – closer to the UI, farther from persistence

UI forms versus models

Using Active Model to abstract form objects

Filter objects or user-driven query building

Filtering in controllers

Moving filtering to models

Extracting filter objects

Filter objects versus form objects versus query objects

Summary

Questions

Exercise

8

Pulling Out the Representation Layer

Technical requirements

Using presenters to decouple models from views

Leave helpers for libraries

Presenters and decorators

Presenters as an abstraction layer

Serializers are presenters for your API

From model to JSON

Serializers as API presenters

Summary

Questions

Further reading

Part 3: Essential Layers for Rails Applications

9

Authorization Models and Layers

Technical requirements

Authorization, authentication, and friends

Authentication versus authorization

Lines of defense for a web application

Authorization models

Domain-less authorization models

Classic authorization models

Authorization enforcement, or the need for authorization abstractions

Extracting policy objects

Shaping an abstraction layer for authorization

Authorization in views

Performance implications of authorization

The N+1 authorization problem in the representation layer

The case of scoping-based authorization

Summary

Questions

Exercise

Further reading

10

Crafting the Notifications Layer

Technical requirements

From Action Mailer to multiple notification channels

Action Mailer in action

Mailers in the layered architecture

Not only emails or adding more notification channels

Extracting notifications layer

Ad hoc abstraction

Using third-party libraries to manage notifications

Modeling user notification preferences

Bit fields and value objects

Notification preferences store

A separate table for storing preferences

Summary

Questions

Exercises

11

Better Abstractions for HTML Views

Technical requirements

The V in Rails’ MVC: templates and helpers

UI without a programming interface

Reusability and design systems

Thinking in components

Turning partials and helpers into components

View components as an abstraction layer

View components for mixed teams

Summary

Questions

Further reading

12

Configuration as a First-Class Application Citizen

Technical requirements

Configuration sources and types

Files, secrets, credentials, and more

Settings and secrets

Production, development, and local configurations versus data providers

Using domain objects to tame configuration complexity

Separating application code from configuration sources

Using specialized configuration classes

Summary

Questions

Exercises

13

Cross-Layers and Off-Layers

Technical requirements

The Rails infrastructure layer and its diversity

Infrastructure abstractions and implementations

Across the layers – logging and monitoring

Logging

Exception tracking

Instrumentation

Extracting implementations into services

Separating WebSockets from Action Cable with AnyCable

Processing images on the fly and off Rails

Summary

Questions

Index

Gems and Patterns

Other Books You May Enjoy

Preface

Ruby on Rails is a powerful and influential open source framework specifically designed to facilitate the rapid development of web applications. As a full stack framework, Rails provides developers with the tools necessary for frontend and backend web development, allowing for the seamless integration of HTML, CSS, JavaScript, and server-side scripting.

At the heart of Rails is the adoption of the Model-View-Controller (MVC) architectural pattern. This pattern divides an application into three interconnected parts: the Model, which pertains to the application’s data and business logic; the View, responsible for the output of the information; and the Controller, which manages the flow of data between the Model and the View.

Alongside MVC, another central pillar of Rails is the convention-over-configuration principle. This philosophy manifests in many predefined settings and defaults within the Rails framework, significantly reducing the number of decisions a developer has to make.

Sticking to MVC-based framework components and leveraging conventions is The Rails Way. It aims to streamline the development process, allowing developers to focus on crafting product features rather than getting burdened by the complexities of taming the framework and its components.

However, as with most things, this initial simplicity can be a double-edged sword. It can sometimes spiral into an intricate labyrinth of complexities, potentially transforming a neatly organized code base into a difficult-to-manage, convoluted mess. This book seeks to equip you with strategies and techniques to help you control your Rails application’s complexity while ensuring maintainability.

We start by exploring the framework’s capabilities and principles, allowing you to utilize Rails’ power fully. Then, we start the layering process by gradually extracting and introducing new abstraction layers in a way that plays nicely with The Rails Way. Thus, the ideas expressed in this book could be considered The Extended Rails Way, the patterns and approaches that can help you enjoy the framework and increase Ruby developers' happiness at scale.

As you conclude this journey, you’ll emerge as a proficient specialist in code design, possessing an in-depth understanding of the Rails framework’s principles.

Who this book is for

This book is for Rails application developers struggling to cope with the ever-increasing complexity of their projects and looking for ways to keep code maintainable and approachable.

This book is a perfect fit for developers who have just launched their first Rails MVP and those who have already encountered difficulties moving forward with a majestic monolith.

The reader will need to have an understanding of core Rails principles (described in the official guides) and have some experience with building web applications using the framework.

What this book covers

Chapter 1, Rails as a Web Application Framework, provides a high-level overview of the framework and its core components specific to it being a tool for building web applciations

Chapter 2, Active Models and Records, focuses on the Rails model layer and how to better leverage its building blocks, such as Active Record and Active Model, to extract responsibilities and prevent God objects.

Chapter 3, More Adapters, Less Implementations, focuses on the design patterns used by Active Job and Active Storage.

Chapter 4, Rails Anti-Patterns?, discusses Rails’ controversial features, such as callbacks, concerns, and globals.

Chapter 5, When Rails Abstractions Are Not Enough, focuses on the Service Object phenomenon in Rails and introduces layered architecture principles.

Chapter 6, Data Layer Abstractions, focuses on extracting data manipulation logic (querying and writing) from models.

Chapter 7, Handling User Input outside of Models, provides an overview of abstraction layers to move user input handling out of models, such as form and filter objects.

Chapter 8, Pulling Out the Representation Layer, focuses on abstractions used to prepare model objects for displaying in the UI, for example, presenters and serializers.

Chapter 9, Authorization Models and Layers, focuses on authorization aspects and the corresponding abstractions.

Chapter 10, Crafting the Notifications Layer, focuses on extracting an abstraction layer to handle logic related to user notifications (email, SMS, and so on.).

Chapter 11, Better Abstractions for HTML Views, discusses abstractions to maintain HTML templates in Rails applications.

Chapter 12, Configuration as a First-Class Application Citizen, discusses the problem of configuring web applications.

Chapter 13, Cross-Layers and Off-Layers, focuses on Rails application infrastructure aspects, such as logging and monitoring, and provides examples of abstraction-driven service extraction.

To get the most out of this book

This book assumes intermediate knowledge of the Ruby programming language and experience in writing web applications with the Ruby on Rails framework. If you haven’t had prior experience with Ruby on Rails, please familiarize yourself with the official guides (https://guides.rubyonrails.org) first.

Software/hardware covered in the book

Operating system requirements

Ruby on Rails 7.1 (many examples will work with earlier versions)

Any OS that runs Ruby

Ruby 3.2 (many examples will work with earlier versions)

Any OS that runs Ruby

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Layered-Design-for-Ruby-on-Rails-Applications/tree/main. If there’s an update to the code, it will be updated in the GitHub repository.

The answers to the Questions in the book can be found at https://github.com/PacktPublishing/Layered-Design-for-Ruby-on-Rails-Applications/blob/main/Answers%20to%20Questions.docx and the solutions to the Exercises can be found at https://github.com/PacktPublishing/Layered-Design-for-Ruby-on-Rails-Applications/blob/main/Solutions%20to%20Exercises.docx

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “All we need to make this code work as we want is to add a couple of has_many declarations to our models.”

A block of code is set as follows:

class User < ApplicationRecord   has_many :posts, -> { order(id: :desc) } end class Post < ApplicationRecord   has_many :comments, -> { order(id: :desc) } end

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

Rails.application.routes.draw do   # The same as: resources :posts, only: %i[index]   get "/posts", to: PostsController.action(:index) end

Any command-line input or output is written as follows:

$ git log --format=oneline -- app/models/user.rb | wc -l

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share your thoughts

Once you’ve read Layered Design for Ruby on Rails Applications, we’d love to hear your thoughts! Please select https://www.amazon.in/review/create-review/error?asin=1801813787 for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781801813785

2. Submit your proof of purchase

3. That’s it! We’ll send your free PDF and other benefits to your email directly

Part 1: Exploring Rails and Its Abstractions

This part is dedicated to the framework, Ruby on Rails, itself. You will learn about design patterns, the architecture decisions behind Rails, and the concepts and conventions powering the framework. You will also learn about Ruby on Rails’ controversies and limitations, which we will try to resolve in the following parts.

This part has the following chapters:

Chapter 1, Rails as a Web Application FrameworkChapter 2, Active Models and RecordsChapter 3, More Adapters, Less ImplementationsChapter 4, Rails Anti-Patterns?Chapter 5, When Rails Abstractions Are Not Enough