Helper Methods: Open Up The Door
Today in class, our instructor told us he'd like us to limit each method to around 7 lines of code. This made sense, based on our understanding of the single responsibiliy principle. Nonetheless, it was alarming -- what if fulfilling that responsibility required several steps? Well, that's when I realized I needed somebody - namely, a helper method.
A helper method does pretty much what it says on the tin - it is a method that helps another method perform it's task. You can use one to extract complicated logic to make a method more readable. You can also use one because you know you're going to be using that functionality frequently (ie: >=3 times).
In a way, the entire premise of Ruby on Rails is that it generates a giant pile of useful helper methods for developers to get their projects off the ground. For example, both "form_for" and "form_tag" are Rails helper methods that take in erb code and create clean HTML.
Rails also encourages that we write our own helper methods. To that end, it comes packaged with a class method, called helper, that declares another method (or a module) is available to help us with anything to do with that class.
Here's an example of how helpers cleaned up my code. I've been working on a side project I'm calling Movie Notebook. One of the goals of this project was to practice creating a functional app, from the ground up, without any instructions or expectations from teachers. Part of that, I knew, would involve writing my very first rspec test suite.
While creating my tests, I realized that I was writing @movie = Movie.create(et cetera) an awful lot. Since I already had five different spec files, I decided that I would create a module that would, among other things, create a movie for me to edit. Check out my module below.
And here are some before and after shots of my tests:
In fact, to get rspec to work at all, you'll need a helper--it's a configuration file found at (in my case) /spec/rails_helper.rb. So it was very easy to include my module in all my extant specs and any I create in the future. I just went into my "RSpec.configure do |config|" block and added "config.include MovieHelper" (though if I'd wanted it just for controller tests, I'd've added ", :type => :feature").
today’s title was courtesy of the Beatles














