Question

I've written a little helper method in my ApplicationController like this:

helper_method :dehumanize
def dehumanize (string)
  string.parameterize.underscore
end

Now I would like to use it in one of my model files, but it seems not to be available there.

I tried also with:

ApplicationController.dehumanize(title)

in the model but it doesn't work.

any clue on how to make it work there?

thanks,

Was it helpful?

Solution

Models generally can't/don't/shouldn't access methods in controllers (MVC conventions), but the method you've written doesn't necessarily belong in a controller anyway - it would be better as an extension to the string class.

I would suggest you write an initializer to add dehumanize to String:

\config\initializers\string_dehumanize.rb

class String
  def dehumanize
    self.parameterize.underscore
  end
end

You will need to restart your server/console but then you can call .dehumanize on any string:

some model:
def some_method
  string1 = 'testing_the_method'
  string1.dehumanize
end

OTHER TIPS

Matt's answer is totally right, but to give you some clarification, you want to make sure that you're calling your methods on objects / instances, rather than classes themselves

For example, you mentioned you tried this:

ApplicationController.dehumanize(title)

This will never work because it's calling a method on a class which is not initialized, not to mention the class doesn't have that method. Basically, what will you expect if you called this method?

The way to do it is to use the method Matt recommended, or use a class method on your model itself, which will allow you to call the model's method directly:

#app/models/model.rb
class Model < ActiveRecord::Base
    def self.dehumanize string
        string.parameterize.underscore
    end
end

# -> Model.dehumanize title
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top