How do I use helpers in rake?

Ruby on-RailsRubyRakeHelper

Ruby on-Rails Problem Overview


Can I use helper methods in rake?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Yes, you can. You simply need to require the helper file and then include that helper inside your rake file (which actually a helper is a mixin that we can include).

For example, here I have an application_helper file inside app/helpers directory that contains this:

module ApplicationHelper
  def hi
    "hi"
  end
end

so here is my rake file's content:

require "#{Rails.root}/app/helpers/application_helper"
include ApplicationHelper

namespace :help do
  task :hi do
    puts hi
  end
end

and here is the result on my Terminal:

god:helper-in-rake arie$ rake help:hi 
hi

Solution 2 - Ruby on-Rails

As lfender6445 mentioned, using include ApplicationHelper, as in Arie's answer, is going to pollute the top-level scope containing your tasks.

Here's an alternative solution that avoids that unsafe side-effect.

First, we should not put our task helpers in app/helpers. To quote from "Where Do I Put My Code?" at codefol.io:

> Rails “helpers” are very specifically view helpers. They’re automatically included in views, but not in controllers or models. That’s on purpose.

Since app/helpers is intended for view helpers, and Rake tasks are not views, we should put our task helpers somewhere else. I recommend lib/task_helpers.

In lib/task_helpers/application_helper.rb:

module ApplicationHelper
  def self.hi
    "hi"
  end
end

In your Rakefile or a .rake file in lib/tasks:

require 'task_helpers/application_helper'

namespace :help do
  task :hi do
    puts ApplicationHelper.hi
  end
end

I'm not sure if the question was originally asking about including view helpers in rake tasks, or just "helper methods" for Rake tasks. But it's not ideal to share a helper file across both views and tasks. Instead, take the helpers you want to use in both views and tasks, and move them to a separate dependency that's included both in a view helper, and in a task helper.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSam KongView Question on Stackoverflow
Solution 1 - Ruby on-RailsArieView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMax WallaceView Answer on Stackoverflow