Old Guy New Trick

An old guys journey to learn how to code.

Reflecting on Rails Inflections


Author: John on September 16, 2014

Recently I re-discovered an issue I ran into about 8 months ago.  I am re-writing an application I created for work.  The first version was written in Ruby 1.9.x and Rails 3.x.  I built the app using sticks and glue - no testing.

We are migrating to Ruby 2.1.x and Rails 4.1.x and rather than copy over the app and tweak it, I wanted to take a better approach, a TDD approach.

It is a pretty simple application, with two main models - Baytech and Device.  A Baytech can have zero to many devices, and a device should only belong to one baytech.

To frameout my two models I used the following:

rails g model baytech
rails g model device

Everything seemed fine at first.  Until I started writing tests and code then I re-discovered a blast from the past.  What I didn't catch was that Rails, with its vast knowledge, pluralized both baytech and device as:

  • bayteches

  • devices

 

Now, all is cool with the plural version of device as devices.  But the plural of baytech is baytechs.  Oh crap, what do I do?

The first time this happened to me, it took me a while to figure out what the heck was going on.  Eventually all roads led me to the file config/initializers/inflections.rb

Taking a look inside this file, I found the following, or something similar:

# Be sure to restart your server when you modify this file.

# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:<
# ActiveSupport::Inflector.inflections(:en) do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
# end

# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
#   inflect.acronym 'RESTful'
# end

To cure my issue, I had to make one small change to this file, making use of inflect.irregular:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'baytech', 'baytechs'
end

Once that change was made, anytime there was a need for the plural version of baytech, Rails knew to use baytechs.  Yeah!

Learn Something New Every Day

Last Edited by: John on November 11, 2015