0

Rails's pluralize method was not working like I wanted (words not in english) so I set out to try my own solution. I started out simple with this method in ApplicationController:

def inflect(number, word)
  if number.to_i > 1
    word = word + "s"
  end      
  return "#{number} #{word}"
end

And called it as such in my view:

<% @articles.each do |article| %>
  <%= inflect(article.word_count, "word") %>
  <%= inflect(article.paragraph_count, "paragraph") %>
  ...
<% end %>

But this got me:

undefined method `inflect' for #<#<Class:0x3ea79f8>:0x3b07498>

I found it weird that it referenced a full-fledged object when I thought it was supposed to be just an integer, so I tested it on the console:

article = Article.first
=> (object hash)
article.word_count
=> 10
article.word_count.is_a?(Integer)
=> true

So I threw in a quick words = article.word_count.to_i, but it doesn't throw a TypeError, it actually doesn't do anything, and still returns the same error: undefined method ``inflect' for #<#<Class:0x3ea79f8>:0x3b07498> in reference to the `inflect(article.word_count, "word") line.

Then I thought maybe inflect was already a Rails method and it was some sort of naming conflict, but doesn't matter what I change the method's name to, it keeps giving me the same error: undefined method ``whatever' for #<#<Class:0x3ea79f8>:0x3b07498>

I then tested it on the console and it worked fine. What's going on?

3
  • 1
    Put your inflect method in ApplicationHelper, not ApplicationController Commented Feb 17, 2013 at 0:05
  • @house9 That did it, thanks! Can you expand on why exactly I should have put it there, and not on ApplicationController? Commented Feb 17, 2013 at 0:24
  • ...added some additional information as the answer Commented Feb 18, 2013 at 2:33

1 Answer 1

1

Put your inflect method in ApplicationHelper, not ApplicationController

by default all code in your helpers are mixed into the views

the view is its own entity, it is not part of the controller, when a view instance gets created (automatically when your controller action executes) it gets passed any instance variables you define in your controller action, but does not have access to controller methods directly

NOTE: you can define methods in your controller to expose them to your views by using the helper_method macro - see this post for more info on that - Controller helper_method

but in general you would define the view helper methods in the helpers classes and not in the controller

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.