Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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 different 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.

like image 361
Daniel Rikowski Avatar asked Apr 25 '10 09:04

Daniel Rikowski


People also ask

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.

What is the use of helper method?

A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML.

How do you call a helper method?

To call another function in the same helper, use the syntax: this. methodName , where this is a reference to the helper itself. For example, helperMethod2 calls helperMethod3 with this code.


2 Answers

The module approach is the direction I would take. I prefer it because of its flexibility and how nicely it allows you to organize your code. I suppose you could argue that they are just another form of mixin. I always think of mixins as direct extensions of a particular class

class Foo
  def hello
    'Hello'
  end
end

class Foo
  def allo
    'Allo?'
  end
end

f = Foo.new
f.hello => 'Hello'
f.allo => 'Allo?'

That always seems very specific, whereas the module approach can extend any class you include it in.

Peer

like image 105
Peer Allan Avatar answered Nov 07 '22 00:11

Peer Allan


If you are going to use that in your controllers and some other code, you can create a mixin and add it to your application controller, from which other controllers derive from, that way you can have it in your controllers, then you can add the module to your other outside classes.

like image 45
Francisco Soto Avatar answered Nov 07 '22 00:11

Francisco Soto