How to Use the Rails Inflector in Your Ruby Scripts

Martin Dittus · 2005-12-06 · code, stuff, tools · write a comment

I've written a Ruby script that extracts keywords from a MovableType-exported plaintext database, and while doing so wanted to include the Rails Inflector so that the script could merge singular and plural versions of the same word. It wasn't that obvious to me how to include the Inflector in Ruby scripts outside of Rails, and I searched for a while until I found the proper usage; so I'll document it here to save other Ruby newbies some time.

In the end it boiled down to finding the proper require statements -- I'm not sure if this is the best way though, so any comments are appreciated. Here's how you do it:

#!/usr/bin/ruby
require 'rubygems'
require 'active_support/inflector'

puts Inflector.singularize('inflections')

Explanation

I've found that you need to require 'rubygems' first, which is to be expected (as ActiveSupport, at least on my system, is a gem). But then it becomes unintuitive.

Because if you then attempt to require_gem 'activesupport', the Inflector isn't made accessible:

$ irb
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require_gem 'activesupport'
=> true
irb(main):003:0> Inflector
NameError: uninitialized constant Inflector
        from (irb):3

...and you can't require_gem 'active_support/inflector', because that's not a valid gem:

irb(main):004:0> require_gem 'active_support/inflector'
Gem::LoadError: Could not find RubyGem active_support/inflector (> 0.0.0)
        from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:204:in `report_activate_error'
        from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:141:in `activate'
        from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:37:in `require_gem_with_options'
        from /opt/local/lib/ruby/vendor_ruby/1.8/rubygems.rb:31:in `require_gem'
        from (irb):4

...but you can do this instead (and it only works after loading the activesupport gem):

irb(main):005:0> require 'active_support/inflector'
=> true 
irb(main):006:0> Inflector
=> Inflector
irb(main):007:0> Inflector.singularize('inflections')
=> "inflection"

Even more confusing is the mixing of activesupport and active_support path names, but I assume that's the difference between the gem's name ("activesupport") versus its location on disk (.../active_support/).

I really should RTFM.

Update 2006-06-29: I helped!


Next article:

Previous article:

Recent articles:

Comments

Comments are closed. You can contact me instead.