Steve Carey
Steve Carey

Reputation: 3014

Is there a benefit to create a helper method for only one use?

I notice in Rails tutorials sometimes the authors make helper methods that are only used one time. This strikes me as ridiculous but while learning ActionCable I noticed that DHH did the same thing in his introduction for ActionCable 2 years ago. So maybe there is a point to it that I am missing. Just for illustration, here is the code from DHH.

# app/jobs/message_broadcast_job.rb
class MessageBroadcastJob < ApplicationJob
  queue_as :default

  def perform(message)
    ActionCable.server.broadcast 'room_channel', message: render_message(message)
  end

  private
    def render_message(message)
      ApplicationController.renderer.render(partial: 'messages/message', locals: { message: message })
    end
end

Now I would just write the perform method something like this, and skip the helper method:

def perform(message)
  ActionCable.server.broadcast 'room_channel', { 
    message: ApplicationController.renderer.render(
      partial: 'messages/message', 
      locals: { message: message }
    )
  }
end

Is there any benefit to the first structure over mine? I only see a pointless abstraction.

Upvotes: 0

Views: 792

Answers (2)

Roma149
Roma149

Reputation: 1431

There's two valid reasons for creating a helper method (or any method for that matter):

  1. To make a piece of code reusable
  2. To make the purpose of the code clear to anyone reading it

I think both are valid on their own. You should ask yourself if creating a helper method will add clarity to the application logic, and make it easier for anybody (even you) to understand what's going on. If that's the case, I think it's fine to create a helper that will only be used once.

In a large application, I find clarity to be generally more important than a few extra lines of code. Someone might even find another use for it later.

Upvotes: 0

Harender Singh
Harender Singh

Reputation: 9

What you have written is fine but in ruby on rails there are processes to follow & it's your own choice to follow or not.

We use helpers for following reasons .

  1. Organise the code well in the application.
  2. Use DRY concept so that , if require same helper method can be use by multiple methods or actions .

Hope it clear the purpose of using helpers in ruby on rails application.

Thanks & Regards Harender

Upvotes: 1

Related Questions