Book Image

Polished Ruby Programming

By : Jeremy Evans
Book Image

Polished Ruby Programming

By: Jeremy Evans

Overview of this book

Anyone striving to become an expert Ruby programmer needs to be able to write maintainable applications. Polished Ruby Programming will help you get better at designing scalable and robust Ruby programs, so that no matter how big the codebase grows, maintaining it will be a breeze. This book takes you on a journey through implementation approaches for many common programming situations, the trade-offs inherent in each approach, and why you may choose to use different approaches in different situations. You'll start by refreshing Ruby fundamentals, such as correctly using core classes, class and method design, variable usage, error handling, and code formatting. Then you'll move on to higher-level programming principles, such as library design, use of metaprogramming and domain-specific languages, and refactoring. Finally, you'll learn principles specific to web application development, such as how to choose a database and web framework, and how to use advanced security features. By the end of this Ruby programming book, you’ll be a well rounded web developer with a deep understanding of Ruby. While most code examples and principles discussed in the book apply to all Ruby versions, some examples and principles are specific to Ruby 3.0, the latest release at the time of publication.
Table of Contents (23 chapters)
1
Section 1: Fundamental Ruby Programming Principles
8
Section 2: Ruby Library Programming Principles
17
Section 3: Ruby Web Programming Principles

Handling errors with exceptions

Raising exceptions is the most common way to handle errors in Ruby. All core methods in Ruby can raise an exception when called incorrectly. The easiest way to get a core method to trigger an exception is to pass it an incorrect number of arguments, as shown in the following code:

"S".length(1)
# ArgumentError (wrong number of arguments)

We can also get a core method to trigger an exception when passing the wrong type of argument:

'S'.count(1)
# TypeError (no implicit conversion of Integer into String)

In almost all cases, any unexpected or uncommon error should be raised as an exception, and not handled via a return value. Otherwise, as shown in the previous section, you end up with a case where the error is silently ignored. In the previous section, you saw an example where the update method using a return value to signal an error resulted in data loss. However, there are other cases where the results are even worse...