加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 是否可以在rake任务中包含一个模块而不会污染全局范围?

发布时间:2020-12-17 01:36:27 所属栏目:百科 来源:网络整理
导读:我想知道 – 是否有可能为rake任务创建私有帮助器,无论我如何尝试它们,它们最终都可以在全局范围内使用,并且可以作为任何对象的方法使用.例如: ## this is what I needmodule MyRakeHelpers def helper_1 end def helper_2 endendinclude RakeHelperstask :
我想知道 – 是否有可能为rake任务创建私有帮助器,无论我如何尝试它们,它们最终都可以在全局范围内使用,并且可以作为任何对象的方法使用.例如:

## this is what I need

module MyRakeHelpers
  def helper_1
  end

  def helper_2
  end
end

include RakeHelpers

task :sometask do
  helper_1
  helper_2
end

## And this should not work:

# global scope
helper_1

"a random object".helper_1

class RandomClass
  def foo
    helper_1
  end
end

解决方法

这对我有用:

module MyRakeHelpers
  def helper
    puts 'foo'
  end
end

module MyRakeTasks
  extend Rake::DSL
  extend MyRakeHelpers

  task :some_task do
    helper
  end
end

简而言之,您可以通过包含(或扩展)Rake :: DSL在不同的范围内使用Rake DSL.从source:

DSL is a module that provides #task,#desc,#namespace,etc. Use this when you’d like to use rake outside the top level scope. For a Rakefile you run from the command line this module is automatically included.

任务使用Rake :: Task#define_task引擎盖,您也可以使用它来编写自己的DSL.

感谢How To Build Custom Rake Tasks; The Right Way关于define_task的提示.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读