Using a Little Bit of Convenience to Save Your Programming Flow

While you’re building software, there will be things that will frustrate you every time you have to write them. Bits of code that look ugly. Or those lines you can never quite remember how to write, so you find an example somewhere else in your codebase to copy and paste. These break your flow! So it’s important to recognize them, and make them more convenient.

For example, you’ll sometimes need custom configuration in your Rails app. Maybe you want some extra app-specific settings. Or maybe the libraries you’re using don’t want to look in config/ for their own configuration files. Normally, you’d do the YAML-ERB-read-Rails.env dance:

  YAML.load(ERB.new(File.read(Rails.root.join('config', 'google_analytics.yml'))).result)[Rails.env]

But that’s kind of ridiculous. And sometimes you’ll forget the ERB, and things’ll break when you’re not expecting it.

In our codebase, we have a simple Settings class to make this more convenient:

require 'settings'

GoogleAnalyticsSettings = Settings.new(:google_analytics)
GoogleAnalyticsSettings.google_analytics_id # => "UA-XXXXXXX-1"

Settings will automatically find the correct configuration file in the config/ directory. Then, it pipes it through YAML and ERB, and uses Rails.env to grab the configuration for the Rails environment. Finally, it wraps everything in an OpenStruct to make accessing the top-level configuration a little nicer. Here’s a gist of a basic Settings implementation.

It’s really simple. But it’s convenient. It’s much easier to remember Settings.new than all that file loading stuff. And these little conveniences add up, and will make your codebase so much more fun to work in.

In your code, can you think of something that annoys you, breaks your flow, or where you have to look up an example every time? Can you find a way to make it easier for you to use?

Pushing through tutorials, and still not learning anything?

Have you slogged through the same guide three times and still don't know how to build a real app?

In this free 7-day Rails course, you'll learn specific steps to start your own Rails apps — without giving up, and without being overwhelmed.

You'll also discover the fastest way to learn new Rails features with your 32-page sample of Practicing Rails: Learn Rails Without Being Overwhelmed.

Sign up below to get started:

Powered by ConvertKit

Did you like this article? You should read these:

Comments