How do I use helpers in rake?
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.
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