Creating Helper Methods To Be Used Within Model

Where do people suggest we create helper methods that are going to be
used within the model to do things like string manipulation.

For instance:

Does anyone have an examples where I would put this and how I would
define it? It would be greatly appreciated.

Your Friend,

You have two options really:

1) Create some custom modules for your functionality then include them
in your model.

module MyStringUtilities
  def make_url_friendly(string)

class Tag < AR::Base
  include MyStringUtilities

2) Write direct extensions to built-in classes

class String
  def make_url_friendly

The above would let you use the syntax you use in your post
( Both have their place. Choose whichever
you feel more comfortable with.

Perfect! I put class String.... end at the end of my
application_helper.rb. I am not sure if tha tis the best place to put
it but right now it makes the most sense. Any better ideas?

Yeah, stick it in its own file in lib, then require it in

only. For something like this, you should put it in the Tag model class (app/models/tag.rb)

John Kopanas wrote:

Good point. Problem is that I use this method in all three... models,
views and controllers. :slight_smile:

So putting it in the lib directory might be the best option. But then
again their might be even better ones out their :-). People?

I think this is merely a mix up of terminology. The word "helper" in
the Rails sense derives from the ViewHelper pattern. I believe the OP
was simply referring to common utility methods used throughout his code.

I would say you should prefer the first method of using modules unless
there is a very strong case for extending builtin objects. I think
going for a module first, and then seeing just how useful certain
methods are before going to a builtin. Extending String is a very
powerful and useful thing, but it can also be dangerous as it clutters
the namespace and could result in conflicts in the future (ex: you
write String#to_url, and two months from now Rails includes a
conflicting version).

my 2 cents...

- Rob

There is one implementation option that is surprisingly void from this
conversation: plugins.

One of the reasons plugins exist is a *better* form of "throw some shit
in /lib and require it"

This smells like a good case for an extension of AR::Base, perhaps.
Look at plugins. They are easy and grand and way better than the hacky
lib approach.

Seth, I fail to see how putting utility, yet project-specific, library
code in lib (where it belongs) is "hacky". Plugins would be completely
overkill for this.

hmmm... plugins does sound really sexy if I look longer term. Very
good idea. Might sound overfill for one small method but surely it
will grow! :slight_smile: