2

I have just come to know that I can't use the method 'pluralize' in the rails console or IRB. Is there anything I don't understand about this?

2.3.0 :001 > pluralize
NameError: undefined local variable or method `pluralize' for main:Object

It gets interpreted well when it's used in the ruby or view file. Why can't I use it in the rails console?

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
Sookie J
  • 823
  • 2
  • 8
  • 16

3 Answers3

6

The pluralize method used in Rails views is defined in ActionView::Helpers::TextHelper. To use it in rails console you need to include it

$ rails console
2.3.3 :008 > include ActionView::Helpers::TextHelper
2.3.3 :009 > pluralize 2, 'man'
=> "2 men"

or call them through the helper variable

$ rails console
2.3.3 :0010 > helper.pluralize(2, 'man')
=> "2 men"
R. Sierra
  • 1,076
  • 6
  • 19
3

It should become clear by looking at the documentation: http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize

pluralize is defined on TextHelper, which means that it is available to your helps and views through ActionView.

You can however use it in rails console like this:

ActionController::Base.helpers.pluralize(...)

Or by including TextHelper:

include ActionView::Helpers::TextHelper
gwcodes
  • 5,632
  • 1
  • 11
  • 20
2

It gets interpreted well when it's used in the ruby or view file. Why can't I use it in the rails console?

Because it was meant to be used from views, not from console (by being defined as an action view helper).

But not all hope is lost. You can access helper methods in console!

helper.pluralize(...)
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367