What's the preferred way to use helper methods in Ruby?

Posted by DR on Stack Overflow See other posts from Stack Overflow or by DR
Published on 2010-04-25T09:45:32Z Indexed on 2010/04/25 9:53 UTC
Read the original article Hit count: 208

Filed under:
|

Disclaimer: Although I'm asking in context of a Rails application, I'm not talking about Rails helpers (i.e. view helpers)

Let's say I have a helper method/function:

def dispatch_job(job = {})
  #Do something
end

Now I want to use this from several places (mostly controllers, but also a few BackgrounDRb workers)

What's the preferred way to do this?

I can think of two possibilities:

1. Use a class and make the helper a static method:

class MyHelper
  def self.dispatch_job(job = {})
  end
end

class MyWorker
  def run
    MyHelper.dispatch_job(...)
  end
end

2. Use a module and include the method into whatever class I need this functionality

module MyHelper
  def self.dispatch_job(job = {})
  end
end

class MyWorker
  include MyHelper

  def run
    dispatch_job(...)
  end
end

3. Other possibilities I don't know yet

...

The first one is more Java-like, but I'm not sure if the second one is really an appropriate use of Ruby's modules.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about best-practices