Helpers for common Controller code

Another newbie question: I want to keep business logic out of my
controller. For example I had a routine that did a slightly
complicated computation and it didn't seem to belong in the
controller. But the calculation has nothing to do with display per-se.
It takes an integer in and returns a different integer.

So I thought to put it in the corresponding helper. Is that the best

Because I note that helpers are not automatically 'included' in the
corresponding controller. I had to add an 'include' to the controller
which seemed a bit lame.

When you see helper, think 'view helper'. They're loaded automatically into templates. They're not loaded into controller, because they're little bits of presentation logic and so don't belong in the controller normally.
It sounds like your complicated calculation belongs in a model


In addition to Nathan's excellent remarks, I'd add:

3) As much formatting as possible in the stylesheet.


Thanks all for the excellent points.

I held back from putting the logic in the model because it really
wasn't model related. It was more of a 'business rule' which takes a
date in and generates two boolean and one date result. The model is a
User table, nothing more.

That's how I ended up with the helper but as you all say, helpers are
more view helpers - as is evidenced by needing to do an explicit
include in the controller.

That’s just it… business rules go in models.

However, it may not go in the User model. Models in Rails are not just data-access objects - they are your domain models. If this code belongs to a User, it goes in the User model.

You can even have models that don’t have a table behind them.

Since I don’t know what this method actually does, I can’t tell you where it should go. However, another option is to make your own class and put it there. The Lib folder is a great place for classes that aren’t models.


class Utility

returns two dates plus the date + 10

def self.do_something_with_date(date)
return 0, 1, date + 10


That class wil be required automatically by Rails, so you can use it where you want. In models, views, etc.

So there’s another option. How you do it depends on what you want to accomplish. It’s most likely that this method you’re referring to has some association with a model, so that’s where I’d put it.

I'd go with Brian's approach, personally. For example, I have a file
in my lib directory that does the rendering of a PDF, which would
otherwise clog up my controlller. I also have Vacation and PTO
calculations in my lib directory for an employee program.