“And” and “or” operators in Ruby

When I first started programming in Ruby, using the and and the or operator always confused me.

Thus I avoided them because I didn’t want to worry about accidentally writing incorrect code. I think a lot of programmers do the same, and it’s a shame because incorporating both and and the or operators can lead to more concise and elegant Ruby code.

First, let’s get the biggest misconception out of the way. The and and the or operator are not the same thing as && and the || operator that most programmers are familiar with. The && and the || operators work to validate some kind of condition while the and and the or operators work more to handle control flow, kind of like your every day if statements.


Let’s talk about and first. The easiest way to think about the and operator is a way to chain methods until a method fails. The English way to think about it is something like, “do this and then do that and then do that, until one of those actions fail”. Let’s say you’re giving a mailman directions on how to deliver mail. You give him a list of addresses to deliver mail to and you tell him to continue delivering the mails until you come across a mail where you can’t locate the address of.

I’m going to try to explain it with some code so that it’s easier to understand. One common thing that we all do when writing code is to assign a value to a variable and then calling a method on that variable. For example,

This is something you would typically do in a Rails controller. You query for an ActiveRecord model, assign it to a variable, and then take an action on that variable instance. In the above example, you can utilize the and operator and write the above like this instead.

The above does in one line what the first example did in two lines with one additional advantage. In the first example without the and operator, the resident.launch! will cause an exception if the resident = Resident.find_by(id: params[:id]) fails and returns nil. However, in the example with the and operator, resident.launch! will only be executed if the resident = Resident.find_by(id: params[:id]) was executed successfully and an actual resident was assigned to the resident variable. Thus, in this specific example, the version with the and operator is more resilient.

How would we write the above example with a standard if statement? It would be something like this.

I think the above code snippet is pretty clear in its intentions too, but I personally prefer the version with the and operator.


Let’s now talk about the or operator. The or operator, like the and operator is meant to chain operations together with one slight difference. As we discussed above, the and operator chains operations together until one operation fails. The or operator on the other hand, chains operations together until an operation works. For example, let’s say we want to raise an exception if resident.launch! fails for whatever reason. Not using the or operator, we could do it like this.

In the above example, we’re launching a resident, and then raising an error if the resident failed to launch. How would we write this utilizing the or operator?

In line 2, we are attempting to launch the resident and if the resident launch failed, we are raising an error. The easiest way to comprehend this is literally read it like English: “Hey resident, launch yourself or otherwise raise an error”.


Ruby comes with a lot of tools included to make writing elegant code easier. I believe that the and and the or operators are one of such tools that make such endeavors easier to achieve. I hope that this post helps demystify what these two operators can do in helping you write better Ruby code.

Ruby Keyword Arguments

Whenever new versions Ruby, Rails, or Android comes out, I quickly glance over the change logs and go, “Oh, neat! That’s a cool feature, I’m going to start using that!”

But, habits are hard to break. In my prior freelance gigs and jobs, whenever I wanted to have default values for parameters in a method, I would always do it this way.

If we wanted the method foo to accept multiple parameters and we wanted them to all have default parameters, we would do this.

And so forth. Apparently in Ruby 2.0, which has been out for awhile (yes, I am slow), something called Keyword Arguments was introduced. So, instead of doing the above where you have to worry about ordering of your parameters, you can simply do

This is essentially the same thing as passing in a hash as a parameter and then setting default values for those parameters before writing the actual meat of your method. In Ruby 1.9, the above foo method would have been written as

I think the keyword arguments version is prettier. After looking more deeply into this, it seemed that in Ruby 2.0, we couldn’t make keyword arguments required. However, Ruby 2.1 introduced keyword arguments. To make keyword arguments required, you simply omit the default value after the key, like this.

Keyword arguments vs positional arguments

Personally, I prefer keyword arguments, because it makes reading code much easier. For example, let’s say that you have a method that calculates profitability of a business. Let’s keep it simple and say that the formula is simply revenue - cost.

The first way will be with positional arguments

If someone was looking at the line where we’re calling the method profit with the parameters 500 and 200, that person may wonder, “Okay, what does 500 and 20 represent?”. He/she would then have to locate where the method profit is and read the method to find out that 500 is the revenue and 100 is the cost. Let’s look at what keyword argument version looks like.

In the Keyword Argument version, it’s clear that 500 is the revenue and 50 is the cost as it’s literally written in the line where we’re calling the method profit. I personally find the keyword argument version much more clear.

Some gotchas

I think most people would agree that keyword arguments is more clear than positional arguments. However, using positional arguments is a more succinct way to write a method, so you’ll have to decide between the two and pick the one that makes sense for the method that you are writing. Personally, if the method only takes one arguments or if the arguments that the method takes in is clear/obvious, I think positional arguments make sense. In all other cases, I prefer keyword arguments.

Also, keyword arguments are essentially a hash disguised as a parameter. Sandi Metz once said in a talk she gave (and I believe in her book Practical Object Oriented Design in Ruby) that a method should take in no more than 4 parameters. If it does, there’s probably another method or an object in there.

This “rule” shouldn’t be broken by passing in one hash with bunch of key/value pairs, and while keyword arguments wouldn’t tempt developers due to its syntactical nature of it looking like actual parameters rather than one single hash, it can still be abused if one wants to take advantage of the fact that ordering of parameters is not important in keyword arguments.

For those of you who weren’t aware of its existence, enjoy writing more clearly defined methods with keyword arguments.

ActiveRecord Optimistic Locking

I briefly covered distributed locks and pessimistic locking here. In this specific post, I’ll cover optimistic locking.

Optimistic locking is just an alternative to pessimistic locking except that it sort of “builds in” locking mechanisms to an entire table and its corresponding ActiveRecord model. In pessimistic locking, you have to manually call with_lock on an ActiveRecord model while in optimistic locking, you introduce a column called lock_version in your database table, which automatically enables optimistic locking.

The lock_version column will be incremented every time a change is committed to the record in question. Thus, if there are two processes accessing the same record, and one process makes an update to the record, the second process won’t be able to modify the record unless it re-retrieves the newly updated data. This can prevent problems that can come with concurrent access to the same data.

This is pretty much straight from the Rails docs but I can’t think of any better way to explain some example usages of optimistic locking, so here goes.

Example 1: Optimistic locking preventing two instances of the same record overriding each other.

Example 2: Optimistic locking preventing deletion of the same record when lock_version is out of date.

To add optimistic locking to an ActiveRecord model, add the column lock_version to your database table with a datatype of integer. Something like this.

lock_version is the default column name that Rails will look for, but you can also customize the column name by overriding an attribute called locking_column within the ActiveRecord model like this.

Personally, I prefer pessimistic locking since I can choose specific instances where I want to lock records. To me, optimistic locking seems akin to the evil (in my mind) default_scope that override default scoping behaviors in ActiveRecord.

I would say optimistic locking is a toolbox that one can grab for, but only do so when there’s a really good reason to do it as it completely overrides out-of-box default ActiveRecord behavior.

Database transactions and distributed locks

Race conditions are something I rarely think about when I’m developing web applications.

This is primarily because when I think of race conditions, my mind automatically jumps to managing threads, which frankly does happen with Android development at times, but rarely in Android development either as long as you utilize the libraries provided by Google.

However, race conditions can happen in web development as well, especially when multiple users are trying to access the same record in the database and modifying it at the same time. This means that you have to ensure that your code can cope with concurrent data access. The standard tools that we use in web development to deal with concurrent data access are database transactions and distributed locks.

In this post, I’ll cover what transactions and distributed locks are, and when to use either of them.

** The sample code is written in Rails, but the concept can be applied to any database backed applications.**


Let’s take a look at a typical create action in ActiveRecord.

The above code creates a new product for a single user. This code is fine, since it’ll only affect one user if it fails. If it fails, you’ll probably get notified by your bug tracking tool and address it individually. Now, let’s look at some more code that works with a user and related products that are associated with the user.

At first glance, the above code looks completely fine. But, it has issues.

  1. What if one of the products of user fails to be added to the user2‘s list of products in the middle of the loop?
  2. What if some other process comes in and runs the code for adding the list of products to user2‘s list of products while the first process is running?

If either of the two happens, the code that we’ve written won’t have its intended affect. In fact, the dataset that we end up with for user2 will make our head spin as we debug what happened to user2‘s records.

This is where we want to use transactions. Transactions is just a general database concept that we can utilize easily in ActiveRecord. All ActiveRecord classes have the transaction method that you can wrap your database calls in. Let’s wrap our loop inside a transaction like this.

Wrapping our code in a transaction will execute the code in a single operation. If any part of the code inside the transaction fails, the entire operation will be rolled back. In our specific example, this has the benefit of ensuring that all of user‘s products will be copied over to user2‘s list of products.

The gist of this whole example is, if you’re ever in a situation where you’re affecting more than one row in a database at a time, group your code together inside a transaction.

When transaction can go wrong

Transactions sound great right? It is until you have two or multiple processes running the same transaction at the same time accessing the same dataset. What happens in this situation is that the two (or multiple) processes running the same transaction will commence at the same time, and make their database commits regardless of the actions committed by the other processes. If we’re working with transactions that update existing records, this can easily create race conditions that can create unpredictable results in our dataset.

Distributed locks

We can remedy the problem of concurrent data access with distributed locks. What locks do is ensure that the locked code only runs in a single thread at a time. This means, that no two concurrent processes can run the same piece of code at the same time, preventing race conditions. In Rails, we have a convenient method that we can call on ActiveRecord objects to lock them.

In Rails, this is referred to as Pessimistic locking.

Let’s see the difference between calling transaction vs with_lock on an ActiveRecord object.

If you look, the transaction method simply opens a begin / commit transaction while with_lock method reloads the record with for update added to the SQL, which prevents any other database connections from loading the record for modification.

So what do I do with this information?

If you’ve ever ran into an issue where you suspected race condition was the culprit, I would begin by inspecting the suspected parts of your codebase where you’re making database calls and wrap hem properly in a transaction or lock records properly.

If you are working on a large production application, it probably doesn’t make sense to go through all of your code that makes database calls and determine whether that line of code is the culprit. Instead, anytime you get a bug report where the user is asking questions that goes something like “why did this happen to my data?”, see if your code is written in a way where concurrent data access could be the culprit.

Form objects in Rails

Most applications have forms that take in a myriad of inputs from the user and saves the information that the user typed into the database.

Rails provides various helpers to build forms that interact with ActiveRecord to easily create and persist user input data into the database. Rails specifically provides form_for, form_tag, and more recently in Rails 5, form_with.

Just as an FYI, while I heavily refer to Rails in this post, this pattern can be used with any web application frameworks. This is a pattern not specific to Rails but can be applied in many different application development environments.

These helpers are very easy to use when you’re working with one data model. For example, let’s say that we’re building an application to manage rooms in hotels. In this application, we need to build a form to create rooms for the hotel so that we can book users to these rooms. Now, because we want to advertise these rooms in an eye-appealing way, we want to be able to attach multiple photos for each room. Here’s an example of the Room model that we’ll be working with.

And our Picture model and the Hotel model are as the following.

Our objective in this blog post will be to build a form to create rooms and one picture in the same form.

accepts_nested_attributes_for – Rails’s answer to nested associations in forms

As stated above, building a form to interact with one model is very easy. We just use one of Rails’s built in form builders and map it to one instance of the model. However, when we want to associate multiple models within the same form, things get a little complicated. Rails provides a built in API called accepts_nested_attributes_for to help us build nested forms that can handle multiple models that have associations with each other. To use accepts_nested_attributes_for to build our Room form, we’ll need to add that to our Room model.

Our form for the Room model will now have nesting to accommodate the pictures association that we’ll be building in. It’ll utilize the fields_for helper within the form.

And our controller to interact with this form will look like

This is the standard Rails way of handling associations within forms. It works, but I’m not a fan of this method due to a few reasons. I’ll go over the Pros vs Cons over this standard Rails way.

  1. It’s built into Rails
    • Yes, this is a pro. This feature is built into Rails which means it’s ready for us to use. Rails team is maintaining the code for this feature and is improving and fixing bugs and we’re relying on their work to build our nested forms. Having other people maintain features that help us build our applications is a pro in my opinion.
  2. Rails handles validations for nested attributes for us and wraps up the operation in a transaction
    • Because this is a feature built into Rails, validations that are defined at the model level will be handled by Rails for us. This reduces the work that we need to do as we’re handing over this responsibility over to Rails.
    • When using accepts_nested_attributes_for Rails will wrap the database operation in a database transaction so that associated records all get saved at once. In our specific example, this means that the new Room won’t be saved unless the Picture data is also correctly entered by the user.
  1. It increases nesting
    • If you take a look at the form with the f.fields_for along with the nested pictures_attributes in the room_params, you can see that accepts_nested_attributes_for helper in Rails increases nesting. I personally prefer avoiding nesting if possible because it makes the code easier to reason about for me.
    • In general, flat code is easier to reason about vs nested code. This is akin to having a lot of nested if statements making code more difficult to reason about.
  2. accepts_nested_attributes for is notoriously difficult to utilize (for me at least)
    • I have no idea why, but every time I reach out for accepts_nested_attributes, I start getting stressed before I even get started. To get accepts_nested_attributes to work, I have to build the form, test it and wonder why it’s not working, see which params are coming into the controller, rework the form, controller, and the model to see which one is at fault, and etc.
    • The error messages from Rails for the accepts_nested_attributes is not very helpful. You’ll just see a bunch of error messages that don’t make much sense and see a bunch of random nils and empty params showing up, making it difficult to debug and getting your form working.
  3. As your application gets more complicated, making changes to your nested forms become more difficult.
    • In this specific example, we are working with only two associations: Room and the Picture. Applications inevitably grow larger in complexity, thus it’s entirely possible that our Room model will acquire more complicated associates and we will have to increase the complexity of our nested form, nested params in our controller, validations in our models, and etc. This makes changes much more difficult to make

Form objects to the rescue

Form objects, while not the perfect end-all solution, can alleviate some of the cons that I listed above that come from using accepts_nested_attributes_for helper from Rails. Within the context of Rails, form objects are essentially plain old Ruby objects that interact that handle the logic required to save your records. You don’t even really need forms to utilize form objects. You can also use them as an intermediary between your incoming parameters and your controllers in strictly API applications as well. Let’s refactor our above code using form objects.

First, remove the accepts_nested_attributes_for and the validates_associated helpers in the Room model.

And create a new Ruby class called RoomForm that looks like this.

If you look at the RoomForm class, you’ll see that it’s just a plain old Ruby object with the ActiveModel::Model module from Rails thrown in there so that we can utilize its various validation helpers. We give the form object three attributes that are needed to create a new room and a picture via attr_accessors and then validate the form object with Rails’s built in validates method. We then give the form object a save method that will create the new room and the picture if the form object passes the validates validations that we defined. It’s also important to note that we wrap the create! operations in a database transaction so that we don’t accidentally create a new room without a picture.

Now we need to modify our RoomsController to use our new RoomForm instead of our Room model.

And finally our form itself

If you actually load up the application and submit the form, everything should work. This refactoring with the form objects have several pros compared to the Rails’s traditional accepts_nested_attributes_for method. Unfortunately, it has cons as well (every pattern has a trade-off in software development).

  1. Eliminates nesting and promotes flat hierarchy
    • If you look at our new form that utilizes the RoomForm and the refactored RoomsController you can see that nesting is completely gone. This new flat hierarchy makes the code easier to reason about and to extend in the future.
  2. Skinnier controller with business logic contained within the form object
    • What usually happens with nested forms that interact with models that have complex associations is that the logic for saving these associations eventually gets long and complicated within the controllers. By moving away the logic for saving these associations out from the controller and into the form objects keeps the controllers tidy and neat.
    • Because we’re moving the business logic of handling saving of data into the form objects, we can reuse these form objects throughout the codebase, keeping our code DRY.
  1. Duplicate validations in both form object and the model.
    • I mentioned how the form objects help our codebase become more DRY, but that isn’t the complete truth. If you look at the validations in our form object, you’ll notice that it’s basically a repetition of the validations in the Room model and the Picture model. Our example is simple so it’s not THAT bad, but as our application grows in complexity, this could cause a toll in duplication.

As you can see, form objects eliminate the cons of using the default accepts_nested_attributes_for helper while introducing new cons. Unfortunately, using this pattern will mean that you’ll have to be willing to make the trade off with the slight increase of duplication in validation code.

At the end of the day…

I personally think form objects are worth integrating into your every day development whenever you start noticing nesting in your forms. I think the increase in validation duplication is worth the trade off in the flat hierarchy that you end up with in your forms and controllers.

This pattern is considered useful enough that there are gems out there that implement form objects form you. Personally, I find implementing form objects to be simple enough to roll out my own and I like the flexibility that I gain from self implementation. For those of you who are interested in using a gem instead, I see that has a lot of stars on GitHub and seems to have a lot of features built in that you can use out of the box. Also, the fact that it’s associated with the Trailblazer framework should give it some credibility.

Different styles of organizing ActiveRecord models

This is something I recently noted while working at my new employer’s codebase.

The platform that I work on at my current full time job is your standard Rails application with some Backbone sprinkled in there for organizing JavaScript code. The first thing I noticed when I started working on this new codebase was that the way the code in ActiveRecord models were written was very different than the codebases that I’ve come across before and the way I like to write my Rails models.

I think a simple example will help explain the differences I’ve noticed a lot better. Normally, when I write a typical model in a Rails app, I like to group different types of code together. For example, I like to put all of my validations in one place, all of my class methods in another, all of my instance methods in another, and etc. For example, let’s say that we have your average User model.

This could be your typical Rails model that represents a User. However, if I rewrite this User model following the style guide of the codebase that I work full time on, it’ll look like this.

See how the ROLES constant was moved to above the validates :role validation and the set_slug and the set_full_name before_save callbacks were moved right above to the methods that they’re calling.

If I’m being 100% honest, I find this coding style to be kind of ugly. However, I’ve noticed that organizing my Rails model this way provides a huge advantage in that I find it easier to dissect the immediate impact of each method, variable, constants, and etc has on my model. The above User model is a very simple example, but in real production applications, you’ll find models that span hundreds or even a few thousands of lines long. In these large classes, it’s a huge advantage to look at a method and immediately know that it’s being called in an ActiveRecord callback, whether the method includes any variables that are required by the model to be valid, and etc.

I still don’t know for sure which style I prefer. The style in the second example is new to me, and I still think it kind of looks ugly, but I have to admit that it gives me a better insight into what the code is actually doing at first glance rather than having to skip around a large Ruby file trying to figure out how the code actually works.

Cryptocurrency madness

This post has nothing to do with software development. Instead, I’ll be ranting about the madness that’s been going on in the cryptocurrency world.

The value of Bitcoin has been shooting to the moon lately and it’s all what everyone’s been talking about. At the time of this writing, Bitcoin is valued at $18,844.99 according to Google.

I remember that around 5 months ago, one Bitcoin was sitting at around $3,000. I also had a friend who was constantly nagging me that I should invest in Bitcoin because I’ll be missing out on an opportunity to build “nation-level wealth”. I actually found him kind of annoying since he would constantly nag me about it. And I find people around me talking about Bitcoins these days kind of annoying too mostly because they more or less just heard about the cryptocurrency hype from the media and are interested in it as a get-rich-quick scheme.

I didn’t buy any Bitcoins then, and I won’t buy any now. I had zero interest investing in cryptocurrencies then and I still have zero interest now.

Here are my reasons why I’m so apathetic when it comes to cryptocurrencies.

Cryptocurrencies have no real intrinsic value

I have no idea how Bitcoin or any of the cryptocurrencies out there can be considered real money. I can’t actually “do” anything real with it, aside from sending them from one person to another. I can’t use a Bitcoin to physically build something nor can I eat it to satiate my hunger. From my perspective as a software developer, it’s just ones and zeroes at the end of the day. To me, a sandwich has more value to me than a Bitcoin even if the market says that Bitcoin is worth over $18,000 (at the time of this writing) and a sandwich $10. At least, I can eat the sandwich…

Some people might respond to this by saying that the currency that we use today isn’t real money either since it’s just paper and we humans put an arbitrary value on them since the government “guarantees” its value. And I would wholeheartedly agree with them. Except that I would still put more value on paper money than Bitcoin in that I can burn it for fire. Fire is a real physical thing that I can do stuff with. I can warm up a house, cook, etc. Bitcoin… hmm, I’m trying to think of something real I can do with it… and I can’t.

Most people talking about cryptocurrencies don’t really understand what cryptocurrencies are

If you have conversations with people who are excited about cryptocurrencies today, you’ll notice that around 95% of them have only recently heard of cryptocurrencies due to the recent rocket-like performance of Bitcoin. In fact, a lot of them are investing in Bitcoins not because they understand nor truly believe in decentralized digital currencies, but because they see it as an easy get-rich-quick scheme.

The interesting thing is, most people investing in Bitcoins right now are looking at the dollar value of Bitcoins and are looking to cash out before the bubble bursts. Most people are looking to get rich in dollars, not in Bitcoins. These people don’t truly believe in Bitcoins nor cryptocurrencies as a way to bring free market capitalism to the currency world, but are rather looking to get rich in US dollars as quickly and as easily as possible.

I’m sure that there are a small percentage of people who are investing in Bitcoins and other cryptocurrencies who truly believe in the concept of decentralized digital currencies, but I wouldn’t be surprised if that number was less than 1%.

Also, if you’re following cryptocurrencies in any way, you probably know that there are other cryptocurrencies other than Bitcoin in the market right now, like Ethereum, Litecoin, and etc. If you ask your average cryptocurrency investor what the difference is between Etherum, Litecoin, and Bitcoin from a broad technical perspective, 99% of the time they wouldn’t know the difference other than the dollar value of each one. Hell, I wouldn’t be able to explain the differences too.

Avoid the masses and stick to what you know and believe in

I don’t believe that Bitcoin nor cryptocurrencies will amount to anything. I do think that blockchains are cool and will transform many industries in the future, but I don’t believe in cryptocurrencies as a store of value. I’m sure that due to the insane rocket-like performance of Bitcoin lately, lots of people will become rich. But I’m sure that once it crashes, there will be lots of people who will lose a lot of money.

I believe in the traditional “work-hard-and-grind” way to build wealth rather than the “gamble your way through get-rich-quick schemes”. Could I make some quick easy cash by investing in cryptocurrencies? Maybe, but I would also become paranoid about losing a bunch of money, and then waste a bunch of time researching Crypto, trying to predict the future value of the different coins… basically all the stuff that I don’t fully understand, never will fully understand, and frankly have zero control over. To me, getting into crypto sounds like a giant waste of time.

All in all…

I don’t care much for crypto. I never had, and I never will. I thought that I would write this post to rant about my annoyance of having to listen to people discussing their latest crypto investments everywhere I go (and also mostly because I couldn’t think of any good software development topics to write about). I’m looking forward to the day when this bubble bursts so that people stop talking about crypto. Or who knows, crypto may go up forever and I would have missed my chance to become rich ¯\_(ツ)_/¯.

Dynamically create methods and scopes in Rails

The active record models with the status columns generally indicate that there are different states that the model can be in.

And usually, when there are status columns within a model, it’s common to query for specific statuses and to check for the status of the model. For example, let’s say that we have an Invoice model that have three different statuses: pending, paid, overdue. Most people would write code for querying for these statuses and checking for the status of the model like this.

This works. Some developers, who are aware of creating scopes may create scopes for the different statuses instead. And also, they may add methods to the Invoice model to determine the status of the Invoices (because you know, refactoring).

The above is definitely better, and I (and a lot of people) would probably go, “Good Enough”, and get along with our lives. But our Invoice model can be made more succinct and more flexible if we utilize a little bit of underutilized Ruby features.

Let’s say that the Invoice model can have a lot more statuses, like 10 different statuses, like paid, pending, overdue, overpaid, underpaid, read, unread, clicked, missing, scammed (Note, some of these status names don’t make sense, I just wanted to quickly come up with 10). Well, that’s a lot of custom scopes and methods you have to write. Thankfully, there’s a little trick to creating scopes with a little bit of Ruby magic during runtime.

For the scopes, we can store the pre-defined statuses in a constant, loop over them, and create scopes during runtime. For the methods that check for the Invoice’s current status, Ruby has this thing called define_method that allows you to define methods during run time.

At first glance, one may go, “Why would I ever use this define_method thingy instead of actually writing the method myself?” Well, in the context of creating methods that check for predefined statuses on the fly, it can be pretty useful in that it can create all of these methods for us rather than us having to write the scopes by hand. To utilize these two techniques so that we don’t have to manually write 10 different scopes and methods by hand, we need to do the following.

  1. Create a constant that defines what statuses the Invoice model is allowed to have.
  2. Loop through the statuses, and for each status, create a scope and then define a custom method using Ruby’s define_method.

Below is how you do it.

Try the refactoring of the Invoice model above and you’ll see that the controller still works as it should. And the Invoice model in this form is much more concise and flexible since if we want to add more scopes and methods that pertain to the status, all we have to add is the new statuses in the Invoice::STATUS constant.

Ruby Safe Navigation Operator

I’ve been working on a new codebase lately and have been seeing an operator that was unfamiliar to me.

It is Ruby’s Safe Navigation Operator. It looks like this &. chained by subsequent methods. After looking into it, I realized that I had read about it in one of the Ruby Weekly newsletters a few years ago.

Most Ruby developers are probably familiar with the try method in Rails. What the try method does is it “tries” to execute a method on an object that may or may not have that method available to it. For example…

As one can see, try allows you to “try” methods that you’re not 100% confident will work on an object you’re invoking on. Ruby’s Safe Navigation Operator is exactly like Rails’s try method. You could write the above code in Ruby starting from Ruby 2.3.0 like this outside of the Rails ecosystem.

Now, I’m not sure how I feel about this operator being introduced in Ruby. I’ve never felt 100% sure if I liked the try method in Rails or not because anytime I used it in my code, I felt unconfident in my code. It made me feel like the code I was writing was weak, as if the variable I was invoking try on, I was designing my code in a way that it was difficult to predict what each of the variables was representing.

But, try was only available within the context of Rails and wasn’t available in Ruby land. Now, with the introduction of the Safe Navigation Operator, I have fear that this can be abused when writing pure Ruby programs. Maybe it can make your code more succinct when used correctly, but I can already see myself itching to abuse this when feeling lazy.

Build RSS feeds with Rails

I started a new position at a company called Modern Message last Monday. I’ll cover how to build RSS feeds in the Rails framework in this post.

One of my first tasks was to build a integration with Contentful ( A bit of a random side note, but Contentful is a blogging platform like WordPress that happens to be focus on API first interface. Thus, for developers who don’t want to build their own blogging platform in their applications, platforms like Contentful can be useful as they provide an interface to write blog posts and an API to consume your blog posts. I’ve never heard of a service like this, so I did some research into it and it looks like this is a new software niche that’s becoming popular these days.

Back to the main topic, one of the feature requests in the Contentful integration project was to expose an RSS feed that the public can consume. I’ll go over how to quickly build one in this post.

Let’s say that we have a model called Book and we want to expose all books that we have. The ActiveRecord model looks something like this.

And our corresponding standard Rails controller looks something like this.

And our config/routes.rb file looks something like this.

Fairly simple so far right? It gets simpler.

In our BooksController, we need to add a block to detect which http request formats our BooksController#index route will respond to. We want it to respond to both html and rss formats. html format because I’m assuming that you already have a corresponding HTML page for the index route. rss format to respond specifically to return rss feeds that the client applications can consume. Let’s modify our BooksController to look like this.

Now, create a new rss feed file at app/views/books/index.rss.builder. This file build the RSS feed that your clients will consume.

Now, if make a HTTP request to the BooksController#index endpoint with the rss format, you will get a response that looks something like this.

And that just about covers how to build RSS feeds within the context of Ruby on Rails!