Tuesday, April 30, 2024
HomeRuby On RailsIntroduction to Ruby on Rails Patterns and Anti-patterns

Introduction to Ruby on Rails Patterns and Anti-patterns



Rails Patterns

Welcome to the primary put up in our collection about Ruby on Rails Patterns and Anti-patterns. In every of the posts, we’ll take a deep dive into all types of patterns you may come throughout whereas working with Rails apps.

Right now, we’ll present what a (design) sample is after which attempt to clarify what an anti-pattern is as properly. To raised illustrate explanations, we are going to use the Ruby on Rails framework that has been round for fairly a while. If Rails isn’t your cup of tea for some cause, dangle on, the concepts (or patterns) described right here may resonate with no matter know-how you wind up utilizing.

However earlier than we leap into explaining what patterns and anti-patterns are, how did we get to the purpose the place we want them? Why do we have to have all this stuff for our software program? Why do we have to design our answer?

Sure, You Are a Designer

Even from early laptop programming days, individuals needed to take care of the design of the packages they have been writing. To write down a program (or software program) is to design an answer for an issue. Once you write software program, you’re a designer—be at liberty to append that to your job title. Designing good options is vital as a result of the software program we write shall be learn and/or edited by others. Additionally, the options we provide you with shall be constructed on by others sooner or later.

Having all this in thoughts, generations of engineers began seeing comparable designs in code and structure all through their careers. People began extracting and documenting customary options to issues. Some would say it’s a pure manner of how we as people perform. We wish to categorize and discover patterns in every little thing, and software program isn’t any exception to that.

Being human, as we’re, patterns began rising an increasing number of as software program engineering received extra advanced. Software program design patterns started to develop and cement themselves with engineers all over the world. Books, essays, and talks got, additional spreading concepts of properly thought out and battle-tested options. These options saved lots of people money and time, so let’s go over the time period design sample, and see what it actually is.

What Is a Design Sample?

In software program engineering, a sample is described as an answer that may be reused to resolve a typical downside. The sample is one thing that’s thought-about a very good follow amongst software program engineers. Since software program engineers set them, they’ll shortly go from patterns to their reverse—anti-patterns—however we’ll get to that later.

A design sample will present you the way in which to the answer however it received’t offer you a chunk of code able to be plugged into the remainder of your software program. Consider a sample as a information for writing well-designed code, however it’s important to provide you with the implementation. Utilizing patterns in day-to-day coding emerged within the late ‘80s, the place Kent Beck and Ward Cunningham got here up with an thought of utilizing a ‘sample language’.

The concept of sample languages got here within the late ’70s by Christopher Alexander in his ebook A Sample Language. You could be stunned, however the ebook is just not about software program engineering however the structure of buildings. The sample language is an organized and coherent set of patterns, every of which describes an issue and the core of an answer that can be utilized in some ways. Sounds acquainted? (Trace: frameworks, one other trace: Rails)

In a while, design patterns in software program engineering grew to become well-known with massive audiences after the legendary ebook Design Patterns by the Gang Of 4 revealed in 1994. Within the ebook, there are explanations and definitions of patterns which might be used these days — Manufacturing unit, Singleton, Decorator, simply to call a number of.

Nice, now that we received acquainted or refreshed our information on design and patterns, let’s discover out what anti-patterns are.

What Is a Design Anti-Sample?

When you consider patterns as the nice guys, the anti-patterns are the dangerous ones. To be extra exact, a software program anti-pattern is a sample that could be generally used however is taken into account ineffective or counterproductive. Typical examples of anti-patterns are God objects that include many capabilities and dependencies, which may very well be extracted and separated into completely different objects.

Frequent causes of anti-patterns in code are many. For instance, a very good one is when the nice man (sample) turns into the dangerous man (an anti-pattern). Let’s say you bought used to utilizing a selected know-how at your earlier firm, and also you gained a excessive stage of competence in it. For the sake of the instance, let’s use Docker. You know the way to effectively pack functions into Docker containers, orchestrate them within the cloud, and pull their logs down from the cloud. Immediately, you get a brand new job the place you could ship entrance finish functions. Since you understand lots about Docker and ship apps with it, your first choice is to package deal every little thing up and deploy it to the cloud.

However, little do you know, the entrance finish apps should not that advanced at your present job, and placing them into containers may not be the best answer. It first feels like a good suggestion, however later down the highway, it proves as counterproductive. This anti-pattern is named “Golden Hammer”.

It may be summed up with the saying, “You probably have a hammer, every little thing appears like a nail”. If you’re actually good with Docker and orchestration of companies, every little thing is a Docker service made to be orchestrated within the cloud.

This stuff occur and can occur. Good guys flip to dangerous buys, and vice-versa. However the place do Ruby and Rails match into this image?

Ruby First, Then Rails

Most folk have been launched to Ruby through the use of Ruby on Rails, a well-liked framework for constructing web sites shortly. I received acquainted with Ruby in the identical manner, nothing flawed with that. Rails is predicated on this well-established software program sample known as Mannequin-View-Controller, or MVC for brief. However earlier than we dive into particulars of the MVC sample in Rails, one massive fallacy that always occurs is utilizing Rails with out studying Ruby correctly.

The Rails framework was one of many go-to frameworks once you had an thought and needed to construct it quick. These days, it’s a complete completely different story, Rails continues to be used, however to not the extent it was in its prime. Being really easy to make use of and run, quite a lot of newcomers got down to construct their net apps utilizing rails new command. What occurred then, alongside the highway, issues began occurring. As a newbie, you might be lured by the velocity and ease of improvement with Rails, and every little thing works so magically and easily at first. Then you definitely see you’ve taken quite a lot of ‘magic’ as a right, and also you don’t perceive what’s going on behind the scenes.

I had this downside, and I’m certain many newcomers and superior newcomers are affected by it. You begin with a framework in hand, you construct on it, and once you attempt to add one thing extremely customized, you possibly can’t, since you’ve used up all of the magic factors from that framework. At that time, it’s important to return to the start and study the fundamentals. Going again isn’t any biggie, occurs to one of the best of us. However the issue grows extra important in case you transfer on with out studying the important issues, like in Ruby. One good ebook that may show you how to on this regard is The Nicely-Grounded Rubyist.

As a newbie, you don’t must learn it from begin to finish. However maintain it by your facet so you possibly can seek the advice of it shortly. I’m not saying that it is best to all of a sudden cease no matter you have been doing and browse the entire ebook, however cease every now and then and refresh your information of the Ruby fundamentals, it’d open some new horizons for you.

MVC: Rails’ Bread & Butter

OK, however what about MVC? The Mannequin-View-Controller sample has been round for ages. It’s been adopted by many frameworks throughout a plethora of languages like Ruby (Rails), Python (Django), Java (Play, Spring MVC). The concept is to have separate parts that every do their job:

  • The Mannequin handles information and enterprise logic.
  • The View is for the presentation of the info and the person interface.
  • The Controller ties the 2 collectively by getting information from the Mannequin and exhibiting the View to the person.

Sounds nice in concept, and it’s glorious when the logic is minimal and your web site doesn’t maintain advanced logic. That’s the place issues get difficult, however we’ll get to that in a second.

MVC unfold out like wildfire all through the online improvement group. Even libraries like React, which is insanely standard lately is defined because the view layer of your net app. No different sample has been popularized a lot that it can’t be shaken off. Rails added the Publish-Subscribe with ActionCable, the place the idea of channels is described because the controller of the MVC sample.

However what are the anti-patterns there, within the so extensively used sample? Let’s go over a number of the commonest anti-patterns for every a part of the MVC sample.

Mannequin Issues

As an software grows and enterprise logic will get expanded, of us are inclined to overcrowd their fashions. Fixed progress can result in an anti-pattern known as the Fats Mannequin.

The well-known ‘Fats Mannequin, Skinny Controller’ sample identifies as a nasty man, some as the nice man. We are going to say that having any of the fats is an anti-pattern. To raised perceive it, let’s get into an instance. Think about we’ve a streaming service like Spotify or Deezer. Inside it, we’ve a mannequin for songs like this:

class Music < ApplicationRecord
  belongs_to :album
  belongs_to :artist
  belongs_to :writer

  has_one :textual content
  has_many :downloads

  validates :artist_id, presence: true
  validates :publisher_id, presence: true

  after_update :alert_artist_followers
  after_update :alert_publisher

  def alert_artist_followers
    return if unreleased?

    artist.followers.every follower
  finish

  def alert_publisher
    PublisherMailer.song_email(writer, self).deliver_now
  finish

  def includes_profanities?
    textual content.scan_for_profanities.any?
  finish

  def user_downloaded?(person)
    person.library.has_song?(self)
  finish

  def find_published_from_artist_with_albums
    ...
  finish

  def find_published_with_albums
    ...
  finish

  def to_wav
    ...
  finish

  def to_mp3
    ...
  finish

  def to_flac
    ...
  finish
finish

The issue with fashions like these is that they change into a dumping floor for the completely different logic that could be associated to a music. This occurs as strategies get added slowly one-by-one over time. The entire mannequin then appears massive and complicated, and splitting the logic into a few different locations may show useful sooner or later.

Proper off the bat, you possibly can see that there are some advisable practices that this mannequin is breaking. It’s breaking the Single Accountability Precept (SRP). It offers with notifying followers and the writer. It checks the textual content for profanities, has strategies for exporting the music to completely different audio codecs, and so forth. Having all this provides to the mannequin’s complexity, and I can’t even think about the take a look at file for this mannequin.

Find out how to refactor this mannequin majorly depends upon how strategies are known as and used elsewhere. I’ll current some common concepts of how we are able to deal with these, and you may select the one that matches your case one of the best.

The callbacks that notify followers and the writer may very well be extracted to jobs. The roles will get enqueued and the logic stored out of the mannequin, like so:

class NotifyFollowers < ApplicationJob
  def carry out(followers)
    followers.every  follower.notify 
  finish
finish

class NotifyPublisher < ApplicationJob
  def carry out(writer, music)
    PublisherMailer.song_email(writer, self).deliver_now
  finish
finish

Jobs will run on their very own within the separate course of, away from the mannequin. Now you possibly can take a look at your job logic individually and simply test whether or not the correct job was enqueued out of your mannequin.

Let’s say that checking for profanities and whether or not the person has downloaded the music is all taking place within the view a part of our app. In that case, we may use a Decorator sample. One standard answer that may get you began shortly is Draper gem. With it, you can write a decorator just like this one:

class SongDecorator < Draper::Decorator
  delegate_all

  def includes_profanities?
    object.textual content.scan_for_profanities.any?
  finish

  def user_downloaded?(person)
    object.person.library.has_song?(self)
  finish
finish

Then, you’d name enhance in your controller, for instance:

def present
  @music = Music.discover(params[:id]).enhance
finish

And use it in your views like so:

<%= @music.includes_profanities? %>
<%= @music.user_downloaded?(person) %>

When you don’t like utilizing a dependency, you possibly can roll your decorator, however we’ll speak about this in one other weblog put up. Now that you just’ve received the vast majority of your mannequin considerations separated, let’s take care of the strategies for locating songs and changing a music. We are able to use modules to separate them:

module SongFinders
  def find_published_from_artist_with_albums
    ...
  finish

  def find_published_with_albums
    ...
  finish
finish

module SongConverter
  def to_wav
    ...
  finish

  def to_mp3
    ...
  finish

  def to_flac
    ...
  finish
finish

The Music mannequin will prolong the SongFinders module, so its strategies can be found as class strategies. The Music mannequin will embrace the SongConverter module, so its strategies can be found on the mannequin cases.

All of this could make our Music mannequin fairly slim and on level:

class Music < ApplicationRecord
  prolong SongFinders
  embrace SongConverter

  belongs_to :album
  belongs_to :artist
  belongs_to :writer

  has_one :textual content
  has_many :downloads

  validates :artist_id, presence: true
  validates :publisher_id, presence: true

  after_update :alert_artist_followers, if: :revealed?
  after_update :alert_publisher

  def alert_artist_followers
    NotifyFollowers.perform_later(self)
  finish

  def alert_publisher
    NotifyPublisher.perform_later(writer, self)
  finish
finish

There are lots of extra mannequin anti-patterns, and this is only one instance of what can go south with fashions. Keep tuned for an additional weblog put up on this collection, the place we’ll go into particulars about extra mannequin anti-patterns. For now, let’s see what can go flawed with views.

View Issues

In addition to mannequin issues, Rails of us can generally wrestle with the complexity of their views. Again within the day, HTML and CSS have been the kings of the view a part of net functions. Slowly over time, JavaScript got here to reign, and nearly all elements of the entrance finish have been written in JavaScript. Rails follows a bit completely different paradigm concerning this. As an alternative of getting every little thing in JavaScript in view, it is best to solely “sprinkle” JS onto it.

In any case, having to take care of HTML, CSS, JS, and Ruby on the identical place can get messy. What’s difficult with constructing Rails views is that the area logic can generally be discovered contained in the view. This can be a no-no because it breaks the MVC sample, for a begin.

One other case may very well be utilizing an excessive amount of embedded Ruby in your views and partials. Perhaps a number of the logic may go inside a helper or a decorator (also called the view mannequin or a presenter). We are going to get into the examples of it in a number of the subsequent posts within the collection, so keep tuned.

Controller Issues

Rails controllers also can undergo from quite a lot of completely different issues. Certainly one of them is a Fats Controller anti-pattern.

Earlier than, our mannequin was fats, however it misplaced some weight, and now we discover that the controller has added some additional weight within the course of. Normally, this occurs when the enterprise logic is put contained in the Controller, however its precise place is within the mannequin or elsewhere. Among the concepts shared within the massive Mannequin part can nonetheless apply to the controller — extracting code to presenters, utilizing ActiveRecord callbacks, resorting to Service objects.

Some of us even resort to utilizing gems like Trailblazer or dry-transaction. The concept right here is to create courses that take care of particular transactions. Transferring every little thing out of the controller and retaining the mannequin skinny, you retailer and take a look at logic inside these separate courses, which some name companies, transactions, actions, and comparable.

Conclusion

There are lots of extra anti-patterns and much more options for them. To attempt to cowl every little thing on this put up will take an excessive amount of area and time and it’ll make our put up look fats (just like the mannequin and controller we talked about). You’ll want to comply with our collection, the place we’ll deep dive into each side of the MVC sample in Rails. There, you’ll learn how to take care of probably the most well-known anti-patterns. Till then, I hope you loved this overview of what patterns and anti-patterns are and the most typical ones within the Ruby on Rails framework.

Till the subsequent one, cheers!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments