views:

20

answers:

2

Is it acceptable to call ActionText from within ActiveRecord?

def last_updated
  updated_at? ? "Updated #{ActionText::time_ago_in_words(updated_at)} ago" : "never updated"
end

Is there an argument against doing something like this? Should this be a helper method?

A: 

Yes. According to strict MVC teachings, it is bad form and belongs in a helper.

In theory: This particular chunk of functionality is presentation specific, therefore by MVC teachings it belongs in a view helper.

In practice: It really doesn't matter. I believe ActionText is parsed when the server/console is loaded. Meaning that the file doesn't need to be loaded again. Also calling the method directly instead of including ActionText is probably better from the memory management side.

No body is going to stop you from adding this code to the Model or force you from doing things the Right Way

Personally I prefer to define these kinds of methods in the model just because I find the syntax of an instance method(model.last_updated) is more aesthetically appealing than that of a helper(last_updated(model)). However the dynamic nature of ruby allows you to do have it both ways. Essentially define instance methods on your model that is only available in views. All it needs is an extra step.

If you're really interested in that extra step, it would look like this:

module ModelHelper 
  def included(base)
    Model.send(:include, ModelInstanceMethods)
  end

  module ModelInstanceMethods
    def last_updated
      updated_at? ? "Updated #{ActionText::time_ago_in_words(updated_at)} ago" : "never updated"
    end
  end
end

Where Model is the class name of the model you want this method to be a part of.

EmFi
A: 

I would suggest placing this in a helper rather than the model. It seems like this method would be used to generate content for a view, which is exactly what helpers are for.

Beerlington