29,99 €
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:
Seitenzahl: 354
Veröffentlichungsjahr: 2023
Discover practical design patterns for maintainable web applications
Vladimir Dementyev
BIRMINGHAM—MUMBAI
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
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.
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.
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.
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.
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.
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.
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
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) } endWhen 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) endAny 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.
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.
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.
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 belowhttps://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
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