reedy.in / words

Topics that require more than 140 characters...

Deep Fetch

Sometimes you come across a piece of code of code that feels more verbose than it needs to be. These code fragments stand out against the rest of the code-base in a Ruby file and can often lead to frustrations and debug issues due to unneeded complexity.

I was pairing with a colleague and we had one of these experiences. We both looked at the section of code in question and knew there should be a more “rubyesque” way.

The original code looked something like the following:

Original Code
1
2
3
4
5
6
7
8
9
10
11
12
13
node = {
  "webserver" => {
    "users" => {
      "admin" => {
        "password" => "some amazing password"
      }
    }
  }
}

if node['webserver'].member?('users') && node['webserver']['users'].member?('admin') && node['webserver']['users']['admin'].member?('password')
  defaults['password'] = node['webserver']['users']['admin']['password']
end

This is a pretty common use case, especially as we are consuming JSON resources that have several levels deep. You can search StackOverview and find any number of solutions. The solution isn’t complex and, while you can certainly download any number of gems to provide a solution, it turns out it only take a few lines of ruby to implement a nested search method.

After writing this post I came across a Gem called deep_fetch which provides a slightly different implementation. Rather than rename the methods throughout this post I wanted to give them a nod for a ready-made gem that provides the same basic functionality.

One Possible Solution

First, this isn’t the only way to solve this problem. That is the beauty of Ruby, there are many ways to implement smart solutions to common problems. Now, lets dive in.

After a brief conversation we decided we wanted our solution to accept any number of keys, returning the value for the last key or false.

Ideal implementation
1
2
3
4
5
node.our_custom_search('webserver', 'users', 'admin', 'password')
#=> "some amazing password"

node.our_custom_search('webserver', 'users', 'jdoe', 'password')
#=> false

Version Control Will Save Your Life

A few months back I had the pleasure of presenting to the TechDawgs student organization at SIU Carbondale. I was given free choice of topic and I decided to try to explain why version control is important.

I believe one of the most overlooked “core” skills that a student should learn is version control. Many tools (and some operating systems) come with some kind of revision system built-in, but anyone serious about development needs to have a firm grasp on how to manually handle versioning in their projects.

When I hire a new student developer to work with me at my day job the first several weeks are spent on introductory training and we hit on aspects of version control using Git throughout the process. There are lots of great resources to teach and explain Git. My favorites include the Try Git course at Code School, the Pragmatic Guide to Git, and the Pro Git book are my top three recommended sources.

If you aren’t intimately familiar with Git, especially using the command line interface, I would encourage you to take the time to dive in. Get to know the basic commands by heart and remember that it is always acceptable to refer to the documentation if you forget a command or argument. It’s more important to do it, than to have it memorized.

If you are interested you can take a look at my slides for the presentation to TechDawgs. And remember, Version control will save your life!

Dynamic Validation in a Rails Model

Since 2005 I have maintained a CMS developed on the Rails platform for my day job. There are a number of people who maintain the content on that page and one of the most requested features was for the content staff to create “dynamic” forms.

Over time our implementation failed for a variety of reasons, mostly due to improvements to Ruby and the Rails framework. The most recent issue hit us with Rails version 3.2.x and completely broke the code. Remedying the issue require rewriting the validation aspects of the code.

Before looking at the fix, I’ll describe how the dynamic forms work. From the administrative section a new Form can be created. A Form has many FormComponents that define the various questions and accepted answers. A FormResponse then takes the questions and answers provided and saves it as an “isolated” snapshot. This allows the form to be updated at-will but does not break the history of responses. For example, a particular option may no longer be available or a question from a form my be removed entirely.

Model Relationship
1
2
3
4
5
6
7
8
9
10
11
12
13
class Form < ActiveRecord::Base
  has_many :form_components, dependent: :destroy
  has_many :form_responses, dependent: :nullify
end

class FormComponent < ActiveRecord::Base
  belongs_to :form
end

class FormResponse < ActiveRecord::Base
  belongs_to :form, include: :form_components
  has_many :form_components, through: :form
end

A FormComponent can be any of the standard form elements, including selects, check boxes, and radio buttons. Accepted answers are stored in a comma separated list and the form is rendered using Rails standard form helpers. Additionally, a form component can be determined to be required, accepted, or match a specific regular expression.

A Blast From the Past

Every 4-5 months I receive an email from someone who has come across an old forum post called HOWTO: Beginning Relationships that I wrote in 2006.

It’s fun to go back and look at that early code. It was aimed at being an absolute beginners guide to starting a Ruby on Rails project. The images are no longer available and I would be hard-pressed to find them in my digital archives, but the content is intact.

Most of the time the questions are the result of differences between Rails 3 and what I am guessing to be Rails 1.x. When I wrote that tutorial the through: option had just been added! However, What always surprises me is there seems to be a decent number of people who are not grasping the most basic concepts, despite the availability of great books1

I’ve been considering re-writing this tutorial to reflect the changes in Rails 3.2.x but tend to stop when I look at the landscape of great beginner resources, the least of which are the well written Ruby on Rails Guides2. It seems, though, that maybe some dead simple beginning tutorials might be helpful for people looking for the concepts rather than the full techniques. This is what Code School3 is great at, but for quick reference it is difficult to hunt through their slides and not everyone will pay for access.

I am regularly training brand new developers, typically students with little to no previous experience in any web development. I plan take with some of our initial conversations related to setup, design, and implementation and turn them into short tutorials. I think I’ll start with a refresh of that 6 and a half year old(!) tutorial on basic relationships.

Thoughts on Format

While writing for this blog, besides finding it extremely difficult to string words together into coherent sentences, I have often wondered about the best format. I hope what I write is worth reading from beginning to end, but will often reference outside material within the body of the post.

I’ve settled on a format I like and used it in the previous post. If I am commenting on a specific article or site I will reference it and provide a link within the first paragraph. Beyond that any links to other resources will occur as footnotes for the post. if you wish to jump to the footnote you certainly may, but by providing all external links in one spot I hope you will read through the whole post before flipping away to another page.

This post is primarily to remind myself of this decision for future writing. Also, to my future self who is reading this, don’t over-think it, just write.

Reminds Me of a Quote

I’ve been watching The West Wing on Netflix lately and often one of the principal actors will rattle off the perfect quote for the situation. While working at the University I’ve met a few people who are able to quote the greats in their field, though rarely verbatim and often the result is to simply show they know the quote rather than a mastery of the situation. I don’t see that a lot within the web development profession.

Perhaps it is because my chosen field is relatively young, we do not have the luxury of 200+ years of speeches to pull from as is the case in The West Wing, or perhaps its because the greatest developers are often hidden behind their code. There are certainly a few cases that disprove my point. Many in the Ruby community look to _why1 and all the work he did in advocating Ruby, quoting from his Poignant Guide2. The recent suicide of Aaron Swartz has pulled people to his writing3 and I’ve seen many quote his work. I think we’ll see even more of this as the Save Publishing4 bookmarklet continues to gain users. However, most developers won’t spend time reading lengthy writing by other programmers. However, with social coding sites we are seeing a different trend emerge.

Just like the great speech writers of history who spend hours reading historical speeches, reciting inauguration addresses, and listening to world leaders, we developers spend our time looking through shared repositories on sites like Github, Bit Bucket, and Google Code. We line ourselves up with programmers who code like we want to code and practice making our code look like theirs. There are strong personalities in our profession and attached is an equally strong sense of style in development. The result is not verbatim quotes, but instead an alignment of coding style. All of our coding practices originated from someone’s idea, from how we name variables to whether we use presenter classes to any other number of development choices. What is important is that we do not stifle our own voice while learning from these greats.

I don’t spend as much time as I would like reading speeches and writings of histories greats, although I am interested in such things. I do, however, spend a lot of time reading the code of developers more talented than myself and I learn from them. We may not have hundreds of years to look back over, but we have a vast amount of knowledge we can look at now. Taking the time to dig in deeper, showing interest in the body of work we pull from, displays a passion for the process and a desire for greater understanding. This is important.

The Recipe

I think my wife is pretty amazing. She is a busy woman. We have four young children that we homeschool. She has been working hard to heal her body from food allergies by following the GAPS diet. She cares for our house, our chickens, and our garden. She is a doula and is regularly consulted by friends with infants and toddlers for advice. Through all that, she lifts me up and makes me into a better man than I would be otherwise.

Both she and I like to cook. One result of the GAPS diet is that all the things I have become good at cooking are no longer legal options for our evening meals. Gone are the nights of whole-wheat pizza crusts or pancakes for supper. It’s taken some adjusting, and I will admit that I’ve been less than enthusiastic about the situation, but through this process my wife has demonstrated this passion to improve again and again. When faced with the question “What’s for dinner?” I am dumbfounded, suggesting “Eggs? Chicken?” whereas she is regularly searching for new and exciting ways to make our meals enjoyable. Often building upon a basic recipe using the knowledge she’s gained through this process. Eventually, she ditches the recipe and relies completely upon her expertise.

Recipes are interesting things. They act like safety nets for us when we’re just beginning. It’s wise to leverage them when we are getting started. This is as true in software development as it is in cooking. Some of the best beginning programming books available are called cookbooks or include the word recipe in the title. This books take common scenarios and provide a basic solution. Often times this is enough to satisfy the requirement and the programmer can then move onto another feature.

There’s a problem with recipes though. If you never deviate from the recipe then you aren’t really improving. You may get better at completing that recipe, but what if you never learn how to substitute ingredients, adjust the yield, or navigate an unexpected problem? Recipes are vital when you are starting, but they can hold you back.

This is what my wife is great at. She can take one or more recipes and improvise to create something better. As programmers we should do the same. Be aware of the recipes, the best practices, but do not limit yourself to them. Aspire to improve the recipes while understanding why they became the best practice.

What we do as developers isn’t always complicated. A large portion of what we do is converting database queries to HTML. It isn’t always glamorous or exciting, but we cannot give into the good enough mentality, that’s when we lose the passion to be great at what we do. Simple shouldn’t result in lazy. In Jiro Dreams of Sushi we see this at an extreme level. Sushi, only sushi, is prepared day in and day out at a level beyond what anyone else is doing. This doesn’t prevent the chef, Jiro, from evaluating every plate to understand what could improve.

Our challenge is to not settle back and use the same recipe over and over, never striving to improve. If you do use a recipe, make sure to tailor it to your own style and demands. A well established recipe aims for the widest adoption, which isn’t necessarily what you are doing in your development.

Refactoring: A Basic Introduction

I work for a University, though not as a professor. I do have the privilege to work with students in a variety of capacities, including web application development. There are several departments on campus that offer web development courses but they tend to focus on basic tasks performed with PHP rather than a greater understanding of the industry and the options within. Over the years I have been able to introduce many students to using Ruby and Rails as well as the underlying concepts perpetuated by agile development.

One of the key concepts is the idea of refactoring. Core to test driven development and essential to keeping your code DRY1, this concept is often not even discussed in the introductory development courses or, if it is taught, is overlooked by the students. Simply defined, refactoring is the process of rewriting code to make it easier to maintain while not altering the behavior of the application. When done well you eliminate complexities while making the code easier to work with. As I look at the attributes of a great craftsmen I see two that can be attributed with refactoring; aspire to improve and maintain cleanliness.

The first weeks of employment of a new developer on my staff consists of going through online courses2 and reading well-written books.3 Then, we spend some time pair-programming where we share one workstation with one of us driving and the other navigating.4 Through this process the new developer often gets their first taste of refactoring code. I have repeated this cycle many times as I train new developers and, the most recent time, I had the idea to document our refactoring for future reference.

Babel by Mumford and Sons

I’m just going to leave this here, Does Marcus Mumford sound like Dave Matthews?.

With that out of the way, let’s get to the sophomore album, released today, by Mumford and Sons. Babel is fantastic. True to the original sound they established on Sigh No More. Each track has fresh instrumentation and the vocals are simple and point to issues that resonate in each of us.

I appreciate the confidence Marcus Mumford has in approaching subject matter such as faith, life, and death. In several instances the vocals stand with minimal accompaniment and express themselves powerfully. On more than one occasion I replayed pieces of a track to really listen to what was being said.

I, poorly, play the banjo and am I huge fan of Winston’s command of the instrument. Do yourself a favor and listen attentively to how precise and technical his playing is, you won’t be disappointed.

If you have a Spotify account, give the album a listen. Then go buy it. These guys are the real deal and I hope they continue to be supported to make great music.

Why So Serious?

I take myself too seriously. At least I think I take myself too seriously. I can often confuse this with perfectionism, of which I also am guilty. I tend only to do the things I know I can be successful at. For that reason, I tend to focus on a specific task, project, or goal and ignore outside influences. This trait tends to make people think I’m pretty serious. Really, I just don’t like to fail.