Words and Code

One writer’s journey from words to code.

A Year of Tuesdays

A year ago, I had this idea: I was going to write things down. To be clear, this wasn’t a novel idea, and definitely not a new one by any stretch of the imagination. But it was something I wasn’t exactly in the habit of doing, and the first day of a new year seemed like the perfect excuse to begin creating this new habit.

So, I decided to start writing down all the things I didn’t know, and make an effort to learn them. I honestly didn’t know what I was going to be writing, and I didn’t know if any of it would be well-written, much less worth reading. All I was sure of was that I was going commit to doing it wholeheartedly, just once a week — not for anyone else specifically, but really just for myself. Thus began a year-long adventure of researching, writing, and sharing all the things I would discover in my first year as a software engineer in my very first developer job.

Today brings me to the end of the road on this journey of Technical Tuesday blog posts. And just like the first day of a new year, the last day of a soon-to-be-gone year is a seemingly perfect time to do some reflecting on a year of Tuesdays.

Composing Microscopic Rails Views With Cells

I crossed over to the dark side awhile ago, and I can hide it no longer. And when I say “the dark side”, what I mean is JavaScript. Surprise, surprise — I am now haunted by semicolons everywhere I go! I’ve been working a lot with Ember and a little bit with React over the past six months, and have both struggled and enjoyed integrating these frameworks with a Rails API. At first, coming back to Rails after a week or so of Ember was just like coming home: warm, comforting, and familiar. Yet the wild west of braces and semicolons called out to me. The more that I worked outside of Rails, the more comfortable I became with more functional programming concepts (read: concepts that are abstracted away such that you don’t ever have to think about them in the Rails framework). After awhile, I noticed that coming back to Rails was less like coming back to something familiar, but instead something that often seemed limiting and constricting in its conventions.

As much as I love the convention over configuration format that Rails brings to the table, there are times when I wish that there was a better way to do something. A lot of my desires lie at the crux of two forms of programming that I respect, and yet see both benefits and drawbacks in: functional programming and object-oriented programming. While JavaScript is an OOP language, libraries such as Redux or Nuclear JS emphasize more functional programming techniques like unidirectional data flow, for example. Ember is very much an object-oriented framework and, similar to Rails, is massive with a decent amount of abstraction hiding what’s actually going on. Yet Ember is also heading in a more functional direction, embracing the unidirectional dataflow approach used in Redux, which Ember refers to as “data down, actions up”.

Without veering too far off topic here, what I’m trying to get at here is this: we can learn a lot from observing how other frameworks (and even other languages!) handle their code when things get messy. I’ve come to respect Ember a lot over the past few months, and one of the many reasons I do is because of how the framework handles encapsulation. Ember has a pretty fantastic way of packaging up view logic into a single, standalone piece of code known as a component. Ember components are powerful because they can be rendered as many times as you need, and contain the logic for how something should appear. This means that we can iterate through an array of objects and render the same component, an encapsulation of how that object should appear, and only change the code in one place should we need to do so. I love how components work, and I’ve wistfully longed for a way to do something similar in Rails views. It turns out that someone else also wanted the same thing I did, except that he actually built it — thank you, Nick! And now we get to play with his creation, which is aptly called the cells gem.

You’ve Got a Friend in Friendly_Id

One of my favorite aspects of programming is the fact that there’s always more than one way to do something. In fact, I think this is probably why I consider the very act of writing and building software to be a far more intutive task, rather than a merely structured, logical, and rigid pursuit. The very notion of no “one single solution” to solving a problem is what makes programming both a critical thinking skill, but also a creative one.

Let me give you an example: a few months ago, I wrote about using slugs and the acts_as_url gem to create human-readable urls for an application I was working on. Rails has a handy to_param method that can be used in conjunction with this gem to generate a hyphen-separated string that can be used in the show route of a resource in place of the object’s numeric id, which is both unreadable and usually doesn’t provide any point of reference for the user. So, here we are, using slugs.

However, just because we did something one way initially doesn’t mean that our way is the only way to do it. Actually, I am certain that there are other solutions — and some of them might actually be more flexible than our approach! This was what I realized very quickly when I recently learned about another gem that solves the same problem of slugs in a different, and rather interesting way! In fact it took what I already knew about using and generating slugs in an url structure to another level by using text-based identifiers in place of ids. Basically, it allows us to query for objects by finding them using their slugs, rather than their ids. Doesn’t this make you super excited? Time to find out more about this approach and become friends with the friendly_id gem!

Breaking the News: Wisper + Pub-Sub

I’ve been rather reflective this past week. This is mostly because the end of this year of technical Tuesdays is now very much in sight, with only a handful more posts left to write. Also, I’ve been going back over old posts and correcting a few spelling and code snippet mistakes that have been brought to my attention (shoutout to all of you who have been proofreading for me!). All of this is to say that I never realized until recently that I’ve covered quite the spread of different topics over the past year!

But here’s the rub: I’m not even close to being done with my list of things I still want to learn more about. And even though that list keeps growing, I’ve noticed that the complexity behind the concepts I’m learning and writing about has begun to slowly change. While I started off focusing on syntax and DSL-specific topics, now those topics have become more theoretical in nature. While I used to write about things like the Rails group_by method and the ampersand operator, now I’m diving into more complex concepts like association callbacks and service objects.

This week took complex concepts to a whole new level. I’m talking about higher-level CS theory that I didn’t even know existed. It all started when I heard someone use the term “pub-sub” (yeah, that’s a thing!). And it stands for publish-subscribe, which is a messaging pattern used in software architecture. If you’ve never heard about this before, don’t worry — I hadn’t either! It’s apparently not all that common in Rails development, but JavaScript promises are a loose example for how they are constructed. But let’s not get carried away with semicolons and such nonesense. How does the publish-subscribe pattern work in Ruby? It’s time to learn all about it!

Functions to Call Upon: ActiveRecord Association Callbacks

No developer knows everything — even if they do know a whole lot more than you do. I was reminded of this fact recently while pairing with a more experienced programmer on a large Ember-Rails project that’s now coming to a close. We were right in the middle of adding some methods to a Rails model when we realized that we actually needed to change something about how one of our model’s ActiveRecord associations worked.

What we wanted to do was rely upon a callback function executing every time an association was created or destroyed. But, we hit a little bit of a wall, since we quickly realized that this wasn’t as simple as we initially thought. The complication came with the fact that we were dealing with a has_many relationship, which meant that we weren’t dealing with a single object, but rather a collection of objects. The developer I was pairing with explained that he knew that there were some methods that ActiveRecord has to achieve what we wanted to do, but he wasn’t sure how they worked exactly, just that he had seen them before elsewhere.

After doing a little research on what resources ActiveRecord provides when it comes to solving this problem in an elegant way, we eventually decided to go another route and use a different callback function. But in the process of pairing, we learned that there are some methods that exist in ActiveRecord that can come in handy in this situation. If we hadn’t been on a tight deadline for the specific feature that we were building, we probably could have devoted more time to learning about these callbacks. So, I decided to come back to these callback functions and dig a little deeper. Interestingly, there really isn’t that much documentation on ActiveRecord’s association callback methods, and nearly no blog posts. This is uncharted territory, my friends! Are you ready? I hope so.

Peeking Under the Hood of ActionController Parameters, Part 2

This blog post is part of a series on strong parameters. Read Part 1 here.

Rails often feels like a black box, with all of the complex logic abstracted away and hidden from view. This leaves behind a clean, convention-abiding framework where form follows function. But another, perhaps less-intentional side effect of all the “metaprogramming away” of this framework’s complexities is a frequent lack on clarity of what’s going on behind the scenes.

In my year of working with Rails, I’ve come to appreciate and respect so many things about it. In fact, I think that there’s something incredibly approachable about Ruby as one’s first programming language, with Rails as its corresponding framework. And of course, there’s something truly unique and welcoming about the Ruby and Rails programming community. All of these factors combined make it so easy for beginners of such different backgrounds to start building applications very quickly.

However, once you get past the intial stage of building applications with the basic CRUD operations, or if you’re trying to build something a bit more complex with added functionality, or trying to integrate with another framework, you eventually hit a wall where you realize that that you’re not completely sure how something works. This can be a hard wall to climb over, especially given the fact that you can start building things very quickly with Rails. Some people have heavily critiqued this aspect of the framework, arguing that it’s detrimential to abstract away so much of what’s actually going on, which makes it difficult for people to understand what their code is truly doing under the hood. I’ve peronally encountered this “wall of abstraction” a few different times, but each time I found some piece of logic that worked differently than I thought it would, it only lead me to learn something new about the framework. Most recently, that lead me down a wild goose chase into the source code for ActionController::Parameters — a class that I didn’t even know existed!

Peeking Under the Hood of ActionController Parameters, Part 1

When you write code every day for a living, it’s easy to get hyper-focused on building out new features and getting things done quickly. What’s much harder is to take a step back and figure out exactly how something is working. Of course, sometimes this happens inherently and without any effort on your part — say for example, when you’re fixing a bug or need to integrate with a third-party service and are forced to understand what’s happening on a more granular level. But generally speaking, that is less common when you’re working a within a framework that you’re already comfortable with and use daily, without giving it a second thought.

I had one of those “take a step back and question everything” kind of moments recently. I was writing a controller for the admin interface of a Rails application, and hit a roadblock. To be clear, there wasn’t anything super complex about the controller I was writing; it had the basic CRUD actions that any controller does, and I had written controllers like it plenty of times before. Yet somehow, when I got to writing the params private method for this controller, I couldn’t remember what methods I needed to use. I was super tempted to open up another controller and just copy and paste the strong parameters from one file into another. But I realized that this wasn’t really going to help me at all. What I really needed to do was grasp how strong parameters worked on a more conceptual level. If I could understand why we use the methods that we use, and to what end, I would never need to even look up the documentation for whitelisting parameters ever again!

So that’s exactly what I did. I decided to peek under the hood of Rails’ ActionController, and set my mind to learning everything there was the know about strong parameters. Spoiler alert: I didn’t completely succeed, and I definitely don’t know everything about whitelisting parameters. But what I did finally come to understand was why we use the methods that we do (think require and permit), and why we invoke them in that order. And hopefully I’ll be able to explain how some that black box magic in Rails actually works!

Methods to Remember Things by: Ruby Memoization

A couple of months ago, I wrote a blog post on some basic Ruby keywords including begin, end, rescue, and ensure. A few days after publishing said post, another Rubyist friend of mine sent me a message telling me to read about memoization. “You basically describe memoization in your post without ever explicitly explaining it,” she had said. At the time, I had added it to my ever-growing list of “things to learn more about”, but promptly forgot to make the time to learn about the concept.

Cut to last week, when I was trying to write a controller action that had to do something a bit more complex than simply render a JSON-formatted response of a given resource. So, I started off by implementing a begin end block to execute a bunch of code that needed to run on it’s own. I remembered writing about how to use these two keywords, so I pulled up my post and was suddenly reminded of…memoization. It turned out that I actually needed to use memoization in this controller action, and had already been using it elsewhere in the very same project! But, I still didn’t understand what it was, or in what way I had been using it so far.

After putting it off for months, it was finally time to learn about this memoization business. For those of us (myself included!) who haven’t quite gotten the memo on memoization, here’s the brief lowdown: the term dates back to the year 1968, when it was coined by Donald Michie, a British artificial intelligence researcher who worked alongside Alan Turing at the Code and Cypher School at Bletchley Park during WWII. The basic idea of a memoization function is that it can “remember” the result that corresponds to a set of given inputs. In other words, it can store the results of an expensive function call by “saving” the result such that when you call the same function again with the same parameters, you don’t need to rerun the function. In the context of computer science specifically, this is a kind of optimization technique that is used to make programs more efficient and much faster. There are a few different ways that memoization pops up in Ruby and Rails, which is exactly what we’ll need to learn about next!

Hunting Down the Scoop on ActiveRecord Scopes

Over the past forty or so Tuesdays — has it really been that many?! — I’ve written on a spread of topics. There’s a slight problem with this: sometimes I forget what I have and haven’t written about. Here’s a case in point for you: last week, I wrote about finder objects, and casually tossed in some scopes into my models. It turns out, I’ve never actually written about how scopes work, or what they really do!

I know, I know, that’s pretty terrible of me. I actually learned about scopes awhile ago, and now I use them fairly often in my applications. However, I got so used to writing them, that I never really thought that much about how they work behind the scenes. In fact, when I sat down to write this post, I had to go on a hunt into the Rails source code and Ruby blogosphere to figure out what was going on under the hood every single time I implemented a scope in my code.

The main reason that I like to use ActiveRecord scopes is because they allow us to specify commonly-used queries, but encapsulate these queries into methods, which we can then call on our models or association objects. However, my hunt lead me to find out that scopes have been around for awhile in Railsland, so they’re not exactly that new. But, what’s interesting about them is how their implementation has changed and grown with different releases of Rails. There’s also a lot of debate over how and when scopes are different from their counterparts, or simpler class methods. But what makes a scope exactly? Well, it’s finally time for us to hunt down the answer to that question.

Digging Into the Finder Object Pattern

Most developers aren’t ever completely happy with their code. I’m no exception to this stereotype — I almost always know that I could probably write a cleaner, more concise method, controller, or class. Usually, it’s a matter of not know the best tool to reach for to refactor my code; eventually, I learn a new pattern or form of encapuslating logic that I later use to make my old code a lot better.

But a few weeks ago, I wrote 100 lines of beautiful code. I’m talking about a goregous, straightforward, no-nonsense class that did a lot in a relatively few lines of Ruby. I still feel pretty proud of it (can you tell?), and part of the reason for this is because I also learned a new pattern while writing this class. I was actually pairing with another developer, and we wanted to try using a rather common Rails pattern to solve a problem we were running into again and again: messy queries in our controllers and models.

We both were familiar with the concept of “skinny controllers” and “fat models”, or the idea that your controllers shouldn’t be responsible for containing the logic specific to a model. However, we also didn’t want our models to get out of control in size, which is exactly what was starting to happen. So, we searched for a workaround, and found our answer in one of the most elegant patterns I’ve seen in awhile: finder objects. Finder objects are simple Ruby classes that encapuslate the logic behind querying the database, and they are hands down, my new favorite kind of Ruby object.