【问题标题】:In Ruby on Rails rake task is calling a function from another rake file在 Ruby on Rails 中,rake 任务正在调用另一个 rake 文件中的函数
【发布时间】:2014-04-28 21:08:44
【问题描述】:

如您所见,我在 rake 文件中定义了一个函数。没问题,效果很好。问题是,当我在 另一个 rake 文件 中声明 def get_user_input 时。在那种情况下,函数会从另一个 .rake 文件中调用你有什么建议吗?谢谢。

namespace :backtest do

  def get_user_input
    if ENV['date_from'].present? && ENV['date_until'].present? 
      # get input...
    else
      abort 'Sample usage: blah blah...'
    end
  end

  desc "Start backtest"
  task :start => :environment do
    get_user_input
    # rest of the code...
  end
end

【问题讨论】:

    标签: ruby-on-rails function rake dry code-duplication


    【解决方案1】:

    你可以这样做:

    require 'rake'
    load 'your_rake_file_name_here.rake'
    get_user_input
    

    【讨论】:

      【解决方案2】:

      将函数移到模块中,问题就消失了。

      namespace :backtest do
      
       Module MY
        def self.get_user_input
          if ENV['date_from'].present? && ENV['date_until'].present? 
            # get input...
          else
            abort 'Sample usage: blah blah...'
          end
        end
       end
      
       desc "Start backtest"
       task :start => :environment do
         My.get_user_input
         # rest of the code...
       end
      
      end
      

      【讨论】:

        猜你喜欢
        • 2011-02-09
        • 2015-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-20
        • 1970-01-01
        • 2013-09-14
        • 1970-01-01
        相关资源
        最近更新 更多