Monday, October 29, 2007

Inflector/environment.rb Bug in Rails

Today I needed to get Rails to grok an uncountable noun "media". Easy you think, right? Just add an inflection rule.

So I went to config/environment.rb, uncommented the Inflection example and modified it with my "media" noun, just like this:
Rails::Initializer.run do |config|
  ...
  ...
  ...
  
  Inflector.inflections do |inflect|
    inflect.uncountable %w( media )
  end

  # See Rails::Configuration for more options
end

# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile

When I tried to run rails console or tests I saw an error like this:
me@Xbook:testapp$ ./script/console 
Loading development environment.
./script/../config/../config/environment.rb:55:NameError: uninitialized constant Inflector
/opt/local/lib/ruby/gems/1.8/gems/actionpack-1.13.5/lib/action_controller/assertions/selector_assertions.rb:525:NoMethodError: undefined method `camelize' for "top":String
/Users/me3x/Development/DSE/mediacast2/apps/testapp/app/controllers/application.rb:4:NameError: uninitialized constant ActionController::Base

The problem turned out to be in the commented-out rails example in environment.rb. The Inflector.inflections block must not be nested within the Initializer.run block.

This fixes the problem:
Rails::Initializer.run do |config|
  ...
  ...
  ...

  # See Rails::Configuration for more options
end

Inflector.inflections do |inflect|
  inflect.uncountable %w( media )
end

# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register "application/x-mobile", :mobile

5 comments:

ry4n said...

Great Post! I've been searching high and low and trying all manner of things to get this to work. I had the code as you did, inside the run block. Moving it was exactly what I needed.

Interestingly enough, I needed to add 'media' as an uncountable noun as well. Thanks a ton!

Tornaydo said...

Great! thanks now i can get ahead with inflections :)

Anonymous said...

Thanks so much, I spent hours on this problem today and your solution resolved it. In my case, I didn't like the default pluralization of 'Hex' to 'Hices', preferring the more conventional 'Hexes'

Anonymous said...

You can solve this problem some better, just change your inflections.rb from
Inflector.inflections do |inflect|
to
ActiveSupport::Inflector.inflections do |inflect|

Uday said...

Thanks a lot for this post. I actually had to prefix ActiveSupport:: as Konstantin's comment suggested.

I also found that

ActiveSupport::Base.pluralize_table_names = false also didnt work inside the initializer block and had to be placed outside.