Rails Tricks


04 Apr

Rails Tricks Issue 1

Hi, this is Greg, bringing you the first edition of the Rails Tricks newsletter.

Thank you for subscribing! I hope you will learn a few things over time.

Let me explain what I consider a "Rails Trick". For me, these are the not so well known features of Rails/Ruby.

Let's see our first one.

I am bringing you a view layer trick this week. We will be looking into conditionally rendering links. Rails has a link_to helper to generate links, but there are not such well-known similar helpers. For instance, there is link_to_if, to conditionally render a link:

bca15b8f-3eb1-4dfe-80f5-232ad53366df.png 56.4 KB

It takes a condition for the first param, the name for the link as the second, and the options to construct the URL as the third. There is also an optional fourth argument to set HTML options for the link.

This helper has a counterpart, link_to_unless, which is the same, except it creates the link if the condition is false.

And there is link_to_unless_current. It takes the name for the first argument, the options to construct the URL as the second, and the optional HTML options as the third. But it only renders the link if the current request URI is not the same as the URL of the link. It can be handy when you don't want to have a link to the current page in your navigation bar.

As I mentioned, I will also try to share a non-Rails trick every week, and the first one will be a vim trick.

Vim has many lesser-known features, for instance, it has a built-in spell-checker. So if you are writing content in vim as I do, it can help to catch spelling mistakes. To enable it, enter vim set spell into the command bar.

That's it for now, see you next week!