2008-03-28

Using Helpers in Models in Rails

This one caught me out a bit, so I'm typing this in here in the hope that nobody else would be caught in the same bit of stupidity.
I had a little method in my application_helper.rb file, it only performed a simple calculation. As an example we could use a method such as:
def addone(value)
value + 1
end

I use this in my views where I need it, but I also wanted to use this same calculation. I started out the right way and I went into the Rails console to try something like:
onemore = addone(10)
but it complained that the method was missing. My mistake was that I tried to use the method as a function without any context. So, here's what you do.
You move your method from application_helper.rb to a file in lib/. In my example I'd create a file like:
module SimpleCalculationHelper
def addone(value)
value + 1
end
end

name the file simple_calculation_helper.rb and put it in lib/. In my application_helper.rb file I add include SimpleCalculationHelper just after the module declaration (typically after line 2). Then in my model where I want to use the method I also add a include SimpleCalculationHelper after the class declaration (typically after line 3).
I can now create a method in my helper that uses addone(), but I can't open console and use addone() - which was my mistake. You can do something like this in your model:
def next_id
addone(self.id)
end

Or something.
Remember to fully restart your web server and your console to make sure there's no evil monkeys in the closets.
It really was as easy as that. Nice and D.R.Y.

PS, only use this if your helpers are non-visual. I.e no HTML or anything signifying style or layout. Just calculations and such.

2 comments:

Rick_R said...

Thanks for this. Was googling for the best approach and came across your helpful explanation.

Pavel said...

Thanks, helped a lot