How do I use helpers in rake?

后端 未结 2 1713
执笔经年
执笔经年 2021-02-02 05:56

Can I use helper methods in rake?

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-02 06:24

    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.

提交回复
热议问题