Shawna C. Scott

Learning to hack, one day at a time

Menu Close

Save yourself pain; make strong params yell at you

I’d like to tell you a (cheesy, overly dramatic) story:

One dark and stormy night, you’re given a ticket that requires you to rename some data columns and rearrange a few form inputs. In your arrogance, you confidently determine this will take you no time at all. Thunder flashes. This is totally not foreshadowing.

You successfully migrate the database. You successfully rearrange the form inputs. All your tests pass. You are feeling pretty self sufficient, like a god/dess among junior developers. You decide, since you are a conscientious team member, to manually fill in the form and watch the magic happen.

Only nothing happens. The form cheerfully proclaims it’s success, but your data has clearly not been saved. You vainly try to find the problem for an hour, but eventually, BAMFness severely deflated, have to ask for help. This is when your boss/mentor discovers within minutes that you’ve forgotten to update the permitted parameters in your controller.

As you may have guessed, it’s my own hubris I’m describing here. But! I have learned something that can help you avoid this terrible tale of woe.

Add this line to your config/environments/test.rb and config/environments/development.rb:

# Raise an error when sending unpermitted parameters
config.action_controller.action_on_unpermitted_parameters = :raise

This lovely little incantation (which you can read more about on the strong parameters repo) will throw an exception when you send unpermitted keys, rather than silently swallowing them. So, instead of this:

You’ll get this:

Never thought you’d be happy to see that page, huh?

Best of luck, and always check your hubris, lest it bring you to ruin. ;D

On Tumblr

Git: Fix that last commit

Ever have that “D’oh!” moment, realizing just after you’ve committed some new change that it needs just one more little tweak? (For instance, leaving in some debugging code. Not that I’ve ever done this.)

Luckily, git’s --amend flag is here for you!

Here’s a post that walks you through using it, and the git documentation on undoing things if you want a more in-depth discussion.

On Tumblr

Testing best practices

One of the things I struggle with the most is not how to implement functionality, but instead how to create functionality that will conform to best practices. By the nature of being new, that spidey-sense isn’t yet completely developed, so I’m always excited to find new tools to help train that part of my brain.

Today, I found Better Specs, an Rspec best practices guide, and you can bet I will have it close at hand for quite a while!

On Tumblr

Tab Completion for Git

My new workflow includes creating a branch with git for every new feature, and adding the Pivotal story ID to the branch name. This gives me branch names that end up looking like this:

add_pulse_inputs_79045950

I don’t know about you, but it only took manually typing out 79045950 once before I started looking for a better way. Luckily, git has auto completion capabilities!

Auto-Completion

If you use the Bash shell, Git comes with a nice auto-completion script you can enable. Download it directly from the Git source code at https://github.com/git/git/blob/master/contrib/completion/git-completion.bash . Copy this file to your home directory, and add this to your .bashrc file:

source ~/git-completion.bash

If you want to set up Git to automatically have Bash shell completion for all users, copy this script to the /opt/local/etc/bash_completion.d directory on Mac systems or to the /etc/bash_completion.d/ directory on Linux systems. This is a directory of scripts that Bash will automatically load to provide shell completions.

Check out Git Basics Tips and Tricks for the full instructions, and make your life easier.

 

On Tumblr: http://junior-dev-lessons.tumblr.com/post/100176396858/tab-completion-for-git

Fixed Height Sticky Footer CSS, via CSS Tricks

I don’t know about you, but I absolutely hate footers that float in the middle of the page if the page has very little content. Like this:

Look at all that whitespace. Ick. I suspect I’m not alone in this, since I rarely see footers that don’t stick to the bottom of the window and then expand to accommodate more content. And yet, it’s not very straightforward how to make that happen. Even good ol’ Bootstrap doesn’t have a class for it.

Twice now, I’ve had to spend more time than I would like using the junior dev answer machines to figure it out.

So, now recorded for posterity:*

Sticky Footer by Chris Coyier @chriscoyier on CodePen

One caveat: This technique only works for fixed-height footers

Properly Factored MVC in Rails Applications

EDIT: After feedback from Katrina Owen Herself, I wanted to include the “much improved” version of the tutorial, as well as Katrina’s amazing five-part series on Golden Master testing


 

Recently, I wanted to learn more about refactoring, and about general best practices for structuring Rails code. Generally, when I’m working on a feature, I don’t spend the majority of my time figuring out how to make something work. I spend most of my time trying to find the best way to make it work.

As a new programmer, though, I have to rely on external resources, since I don’t yet have that internal lexicon of good and bad design patterns to point me in the right direction. So, this past weekend, I decided that I wanted to learn more about Rails best practices, and about refactoring. Imagine my delight when I found this great workshop and accompanying tutorial, “Properly Factored MVC”  [tutorial] (see edit) from RailsConf 2013, presented by Katrina Owen and Jeff Casimir.

I finished the video, although I haven’t worked all the way through all the tutorial iterations yet, and I’ve already learned a lot about the theory of refactoring, and how to insure your refactoring doesn’t cause regressions.

If the 1:43 runtime of the video is daunting, you can just work through things from the tutorial alone. Personally, though, I found the video helpful, since Katrina Owens is talking through her thought process as she goes in more detail.

Hope you find this resource helpful!

PS: If you feel inspired to help refactor some Real Live Code ™ after this, feel free to hop on over to the very beginner-friendly open source project, Calagator. I’m a contributor there, and there’s plenty of places to test and expand your skills!

On Tumblr: http://junior-dev-lessons.tumblr.com/post/99540321305/properly-factored-mvc-in-rails-applications

Make your commits better with interactive rebase and -p

 

Yesterday, I finished up the initial code for my third feature at work (Yes, I can still count them on one hand). It came time to submit my code for review, and I realized I had done this to myself:

[Image description: A screenshot of the shell output of running the command ‘git status.’ It shows dark pink text on a black background, showing 38 modified, deleted, or new uncommitted files.]

This is why you commit early and often, folks. So it’s not 4:30 on a Friday afternoon, you’re the last one in the office, and you’re late picking up your wife because you’ve been trying to make Perfect Commits (TM), which means you didn’t commit anything at all for days at a time until it was done. Hypothetically. Not that that happened.

What I should have done is commit things along the way in logical chunks. But sometimes, when you’re a noob and you’re not entirely sure where you’re going until you get there, it’s hard to know what a ‘logical’ chunk looks like.

If you also want to commit more often, but not have messy, half-done features committed over and over, there are two git tools that can make your life easier.

Strategy 1: Commit broken things however much you want. Use git rebase --interactive to rewrite your history once the path is a little more clear.

Caveat: You should only use this strategy when your code is isolated while you’re working on it, i.e., you’re the only one working on your topic branch. Otherwise, when you rewrite history, you risk completely borking other people’s histories if they’re based on the one you just rewrote out from under them.

Strategy 2: Commit often, but use the --patch or -p flag to interactively choose chunks of code (rather than full files) to add, stash, or checkout. This strategy is great, especially when you can’t rewrite history.

on tumblr: http://ift.tt/1pEliO4

New Job, and Junior Dev Lessons

I haven’t announced it here until now, but recently I was hired at a startup called:

38_Zeros_Logo

 

We make a data logger that connects to our cloud aggregation service. We’re doing everything from making custom boards to embedded programming to data cleaning, all with a web-based Rails GUI on top. I’m three weeks in, and absolutely loving both the work and my coworkers!

Currently, I’m working on the Rails app, so I’m using Ruby daily, which is awesome. And because our software team is small and the app is young, I’m living the dream of helping to establish code conventions and working mostly on greenfield problems. And when I’m not feeling like working on Rails for a bit, there’s plenty of room for me to learn more anything about embedded programming and hardware.

Here’s where I work:

Why yes, that is an arctic exploration pod. Why do you ask?

I’ve blogged about code here before, and will continue to on occasion, but I often put off blogging because I feel like I don’t have something ‘big enough’ to say. Simultaneously, I’ve been feeling the need to catalog some of the things I’ve learned, and some of the silly things I’ve done, in the hopes that my pain can help someone else avoid headaches in the future.

So, I’ve decided to launch a Tumblr specifically for small snippets and quick tips that junior devs may find helpful. Tumblr just feels like a more natural place for something intended to be short form. Junior Dev Lessons posts will crosspost here, on their own page. If you want to follow those tips on Tumblr, you can go to junior-dev-lessons.tumblr.com.

If you want to share junior dev lessons you’ve learned the hard way, contact me and I’ll post them, too! Maybe we’ll save some other junior devs some headaches along the way.

Preparation for “The Case for Junior Developers”

On Thursday, June 26th I’ll be giving my second-ever conference talk at Open Source Bridge! The talk is called “The Case for Junior Developers,” and is meant to explore when and where it makes business sense to hire junior developers, some strategies for overcoming common obstacles to hiring juniors, and how to support juniors in a sustainable way for both them and your business.

Here’s where I need your help! I need to hear from you how companies engage (or don’t) with junior developers, and why. Please take a few minutes and let me know by filling out the form below. Thanks!

Regular Expressions

When I was first learning about what regular expressions are and how to use them, I was having a harder than average time finding good resources to explain the basics. Luckily for me, I have an amazing community that came to my aid. Andrew Lorente wrote this awesome post, and Cory Kolbeck wrote this one explaining the bones of using regexes.

I wanted to write about regexes, but the write ups from Andrew and Cory are far and away better than any intro I could write. So, I wondered for a while what I could contribute to the discussion. Then a friend who just graduated from Epicodus mentioned that she understood how to construct regexes (use Rubular!), but not really how they would integrate with an actual program. And I have done that! So, here is a description of how my pair partner and I used regexes as an integral part of solving PCS’s code challenge 4.

For our code challenge, we had to parse and clean a text file of data in this format:

[prefix] [first_name] [middle_name | middle_initial] last_name [suffix] phone_number phone_extension

where anything in square brackets is optional, and then appropriately assign the parts that are present to the correct column in a CSV. We used OptionParser to create our own flags to run a command line script that would do all this.

The way my pair partner and I ended up solving this problem was by creating two scripts. The first script read in the raw data, stripped off the first word in every line of that data and created a reverse sorted histogram*, and then wrote that histogram data to a CSV. We then examined the output and determined which of the words were legitimately prefixes. This is the script we used:

histogram = Hash.new(0)
 
while line = gets
  prefix = (/^S*/).match(line)
  prefix = prefix.to_s
  histogram[prefix.to_sym] += 1
end
 
histogram = Hash[histogram.sort_by { |prefix, count| count }.reverse]
histogram.each { |prefix, count| puts "#{prefix} #{count}" }

We needed to do the same for the suffixes, so we had to split the raw data into the name portion and phone number portion in order to expose the last word of the name section. At this point, we used a regex to match the tab whitespace separating those two parts of the data, saved the first part to a variable, then ran it through a similar script to create a histogram for the suffixes.

Once we’d done that, we set up OptionParser to take the prefixes and suffixes files as input, used those lists to break up the name parts of the data, then used digit matching regexes to both match the existing phone information and reformat it in a consistent way. You can see the source code for the cleaning script. Please forgive our horribly verbose code. Hopefully I’ll get around to refactoring it soon, but for now, done is better than perfect.

So, hopefully this will be helpful to someone looking for some way to actually use regexes in their code! If you feel like playing around with the scripts we wrote, the regexes therein, and OptionParser, you can clone the project and run it in your command line. In your terminal, follow these steps:

shawnacscott in ~/Code on master #%
+ git clone https://github.com/shawnacscott/pcs_code_challenge_04.git
Cloning into 'pcs_code_challenge_04'...
remote: Counting objects: 128, done.
remote: Compressing objects: 100% (86/86), done.
remote: Total 128 (delta 54), reused 103 (delta 32)
Receiving objects: 100% (128/128), 382.55 KiB | 541.00 KiB/s, done.
Resolving deltas: 100% (54/54), done.
Checking connectivity... done
 
shawnacscott in ~/Code on master #%
+ cd pcs_code_challenge_04
 
shawnacscott in ~/Code/pcs_code_challenge_04 on master<>
+ ruby clean.rb --prefixes prefix_words.txt --suffixes suffix_words.txt --input raw_customers.txt --output customers.csv

*a hash where the first word is the key, and the value is the count of how many times that word is present.