ActiveSupport::Inflector and you!


Ruby on Rails is a framework that has convention over configuration in mind. In part of having this paradigm in place, Rails expects certain files to be located in particular places with file names matching the class definition within that file. A quick example is that of the quintessential model in most all information systems; the user.

# app/models/user.rb
class User < ActiveRecord::Base  
  def name
    [first_name, last_name].join(" ")

With this model in mind, within Rails console, the way to access the model, you would do:

$ rails c
Loading development environment (Rails 4.1.4)  
[1] pry(main)>
  User Load (0.6ms)  SELECT  "users".* FROM "users"   ORDER BY "users"."id" ASC LIMIT 1
=> "Zac Hallett"

This is all fine and dandy if you don’t have any models, classes, modules, etc that could be named OAuth for example.


As stated in the setup section, Ruby on Rails follows the idea of convention over configuration. With that in mind about file paths and class / module names, to achieve a class / module name of OAuth, you would need to name the file app/models/o_auth.rb. If you add a class file of app/models/oauth.rb with the hopes you can have the class definition of

# app/models/oauth.rb
class OAuth < ActiveRecord::Base  

you will run into uninitialized constant OAuth (NameError) when trying to access this class via OAuth.

$ rails c
Loading development environment (Rails 4.1.4)  
[1] pry(main)> OAuth
=> uninitialized constant OAuth (NameError)

In order to keep the filename sane, as well as gain the camel casing you seek, you will want to add an acronym to the ActiveSupport::Inflector.inflections singleton instance. In order to add this acronym, add it to the following file: config/initializers/inflections.rb

# 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 'OAuth'

Now you can call your model just like you expected :)

$ rails c
Loading development environment (Rails 4.1.4)  
[1] pry(main)> OAuth
=> OAuth


ActiveSupport::Inflector Documentation